# XXTouch English Full Documentation Context

> Complete English Markdown context for XXTouch documentation, generated from source docs during build.

This file is generated from the source Markdown files during the site build.

Document count: 633

---

Source: [About XXTouch](https://xxtouch.app/en/docs/index.md)
Path: README.md

# About XXTouch

XXTouch uses Lua as its scripting language. It fully supports the syntax and standard library of Lua 5.3, with extensions for color picking, color matching, simulated touch and keyboard events, and more. All scripts must be encoded in UTF-8.

---

- [Developer & tooling downloads](/en/docs/handbook/supplement/dev-tools.md)
- [Developer Handbook](/en/docs/handbook/index.md)
- [OpenAPI](/en/docs/OpenAPI/index.md)
- [XPP Script Bundle](/en/docs/XPP/index.md)
- [XUI Library](/en/docs/XUI/index.md)
- [URL Scheme & QR Protocol](/en/docs/URLScheme/index.md)
- [FAQ](/en/docs/FAQ/index.md)

---

Source: [Handbook Index](https://xxtouch.app/en/docs/handbook/index.md)
Path: handbook/README.md

# Handbook Index

## How to Read This Handbook

- Basic Lua knowledge is required. See the [Lua 5.3 Manual](https://www.lua.org/manual/5.3/manual.html) and [Lua 5.3 Function Reference (ZH)](https://www.zybuluo.com/havonz/note/564563).
- Numbers prefixed with `0x` in examples are hexadecimal.
- Optional parameters are enclosed in square brackets `[]`.
- When a parameter or return value is a table with a fixed structure, curly braces `{}` describe its shape.
- In type descriptions, "Text" and "String" both refer to Lua's `string` type, but "Text" typically implies printable plain text.
- Chapters or sections prefixed with an exclamation mark (!) indicate the function or module may implicitly **yield** (other [threads](thread/README.md) may execute before the function returns).
- Unless otherwise stated, example code does not handle edge cases and should not be copied directly into production scripts.

---

- [Development Tools Download](supplement/dev-tools.md)
- [How to Use XXTouch](how-to-use/README.md)
- [Protect Scripts, Properly Use require](secure-require/README.md)
- [Global Variables](globals/README.md)
- [Basic Control Functions](control-flow/README.md)
- [Development Helper Functions](develop-helper/README.md)
- [Screen Module (screen)](screen/README.md)
- [Touch Module (touch)](touch/README.md)
- [Key Module (key)](key/README.md)
- [Hardware Mouse Module (mouse)](mouse/README.md)
- [Hardware Gamepad Module (gamepad)](gamepad/README.md)
- [Text Element Module (ui_element)](ui_element/README.md)
- [System Module (sys)](sys/README.md)
- [Pasteboard Module](pasteboard/README.md)
- [Dialog Module](dialog/README.md)
- [Clear Module](clear/README.md)
- [App Module](app/README.md)
- [Device Module](device/README.md)
- [Image Object Module](image/README.md)
- [CoreML Module](coreml/README.md)
- [ONNX Runtime Module](onnxruntime/README.md)
- [Process Dictionary](proc/README.md)
- [Thread Module](thread/README.md)
- [WebView Module](webview/README.md)
- [XPP Package Module](xpp/README.md)
- [XUI Config UI Module](xui/README.md)
- [Extended Table Module](ext-table/README.md)
- [Extended String Module](ext-string/README.md)
- [HTTP Module](http/README.md)
- [FTP Module](ftp/README.md)
- [JSON Module](json/README.md)
- [PLIST Module](plist/README.md)
- [Utils](utils/README.md)
- [File Module](file/README.md)
- [VPN Config Module](vpnconf/README.md)
- [System Callbacks](system-callback/README.md)
- [Integrated Open Source Libs](open-source/README.md)
- [Appendix](supplement/README.md)

---

Source: [How to Use XXTouch](https://xxtouch.app/en/docs/handbook/how-to-use/index.md)
Path: handbook/how-to-use/README.md

# How to Use XXTouch

---

## Where are scripts and related assets stored on device?

| Category | Path variable | Rootful path reference |
| --- | --- | --- |
| Resources | [`XXT_RES_PATH`](../globals/README.md#xxt_res_path) | `/var/mobile/Media/1ferver/res/` |
| Scripts | [`XXT_SCRIPTS_PATH`](../globals/README.md#xxt_scripts_path) | `/var/mobile/Media/1ferver/lua/scripts/` |
| Built-in script modules | [`XXT_LUA_PATH`](../globals/README.md#xxt_lua_path) | `/var/mobile/Media/1ferver/lua/` |
| Plugins | [`XXT_LIB_PATH`](../globals/README.md#xxt_lib_path) | `/var/mobile/Media/1ferver/lib/` |
| Logs | [`XXT_LOG_PATH`](../globals/README.md#xxt_log_path) | `/var/mobile/Media/1ferver/log/` |
| Inference models | [`XXT_MODELS_PATH`](../globals/README.md#xxt_models_path) | `/var/mobile/Media/1ferver/models/` |
| Legacy OCR language data | [`XXT_TESSDATA_PATH`](../globals/README.md#xxt_tessdata_path) | `/var/mobile/Media/1ferver/tessdata/` |

These path variables are dynamically resolved at runtime according to the installed edition.

## Pre-sale and installation Q&A

- [View here](/en/docs/FAQ/index.md)

## User guides with screenshots

- [View here](/en/docs/ABC.md)

## Development and community

- [Developer & tooling downloads](/en/docs/handbook/supplement/dev-tools.md)
- [XXTouch technical chat](https://t.me/xxtouch_chat)

---

Source: [Protect Scripts, Properly Use require](https://xxtouch.app/en/docs/handbook/secure-require/index.md)
Path: handbook/secure-require/README.md

# Protect Scripts, Properly Use require

---

## Why can require be a security risk?

- Encrypted XXTouch script modules can be imported by other scripts or modules via [require](https://www.lua.org/manual/5.3/manual.html#pdf-require).
- When your encrypted script is loaded via [require](https://www.lua.org/manual/5.3/manual.html#pdf-require), the global environment is untrusted; functions your script calls may have been replaced.

## How to use require safely?

- XXTouch guarantees some module functions are restored to their initial state before the script is loaded via [require](https://www.lua.org/manual/5.3/manual.html#pdf-require). This covers all functions in `os`, `io`, `string`, `device`, `http`, `file`, and `table`.
- You can deep-copy the global environment into a module-local environment to safely call the above modules' functions. Example:
  ```lua
  -- Put this at the very top of your script
  local _ENV = table.deep_copy(_ENV)
  -- script body below
  --
  -- Finally, you may return exported functions or constants
  ```
- When a module is loaded via [require](https://www.lua.org/manual/5.3/manual.html#pdf-require), the global variable `been_require` is unconditionally set to `true`. You can use it to detect whether the current script is being loaded by require. Example:
  ```lua
  -- Put this at the very top of your script
  if been_require then
      return -- exit immediately if loaded via require
  end
  -- script body below
  ```

---

Source: [Global Variables](https://xxtouch.app/en/docs/handbook/globals/index.md)
Path: handbook/globals/README.md

# Global Variables

Lua has no constant type, so some global variables are used to represent constants.

The path variables below are resolved at runtime according to the installation flavor. You normally do not need to care about the exact paths; on rootless or TrollStore editions the paths may live under a different mount point. If you need to construct a path under the system root manually, see [`jbroot`](/en/docs/handbook/develop-helper/jbroot.md).

---

## Paths

### XXT_HOME_PATH

XXT home directory
Rootful edition: `/var/mobile/Media/1ferver/`

### XXT_RES_PATH {#xxt_res_path}

XXT resources directory
Rootful edition: `/var/mobile/Media/1ferver/res/`

### XXT_SCRIPTS_PATH {#xxt_scripts_path}

XXT scripts directory
Rootful edition: `/var/mobile/Media/1ferver/lua/scripts/`

### XXT_LUA_PATH {#xxt_lua_path}

XXT Lua extension library directory
Rootful edition: `/var/mobile/Media/1ferver/lua/`

### XXT_LIB_PATH {#xxt_lib_path}

XXT C extension library directory
Rootful edition: `/var/mobile/Media/1ferver/lib/`

### XXT_LOG_PATH {#xxt_log_path}

XXT logs directory
Rootful edition: `/var/mobile/Media/1ferver/log/`

### XXT_MODELS_PATH {#xxt_models_path}

XXT inference models directory
Rootful edition: `/var/mobile/Media/1ferver/models/`

### XXT_TESSDATA_PATH (Deprecated) {#xxt_tessdata_path}

XXT legacy OCR language data directory
Rootful edition: `/var/mobile/Media/1ferver/tessdata/`

## Status

### IS_TROLLSTORE_EDITION

Whether the current build is the TrollStore edition

---

Source: [Basic Control Functions](https://xxtouch.app/en/docs/handbook/control-flow/index.md)
Path: handbook/control-flow/README.md

# Basic Control Functions

---

- [Exit script (os.exit)](os.exit.md)
- [Restart script (os.restart)](os.restart.md)
- [Register exit callback (register_atexit)](register_atexit.md)
- [Run code when the script is terminated](terminate-callback.md)

---

Source: [Development Helper Functions](https://xxtouch.app/en/docs/handbook/develop-helper/index.md)
Path: handbook/develop-helper/README.md

# Development Helper Functions

---

- [Print to buffer (print)](print.md)
- [Get printed buffer content (print.out)](print.out.md)
- [Network log (nLog)](nLog.md)
- [Get jailbreak-root path for a system-root path (jbroot)](jbroot.md)
- [Get system-root path for a jailbreak-root path (rootfs)](rootfs.md)
- [Get elapsed milliseconds since script start (get_elapsed_ms)](get_elapsed_ms.md)

---

Source: [Screen Module (screen)](https://xxtouch.app/en/docs/handbook/screen/index.md)
Path: handbook/screen/README.md

# Screen Module (screen)

---

- [Initialize rotation coordinate system (screen.init)](screen.init.md)
- [Get screen size (screen.size)](screen.size.md)
- [Get screen scale factor (screen.scale_factor)](screen.scale_factor.md)
- [Keep screen active (screen.keep)](screen.keep.md)
- [Unkeep screen (screen.unkeep)](screen.unkeep.md)
- [Get color at a point (screen.get_color)](screen.get_color.md)
- [Get RGB color at a point (screen.get_color_rgb)](screen.get_color_rgb.md)
- [Multi-point color matching (screen.is_colors)](screen.is_colors.md)
- [Find color (color-similarity mode) (screen.find_color)](screen.find_color-cs.md)
- [Find color (color-offset mode) (screen.find_color)](screen.find_color-co.md)
- [Capture screen image (screen.image)](screen.image.md)
- [! OCR text in region (screen.ocr_text)](screen.ocr_text.md)
- [Find image on screen (screen.find_image)](screen.find_image.md)
- [Rotate coordinates (screen.rotate_xy)](screen.rotate_xy.md)
- [Inverse rotate coordinates (screen.unrotate_xy)](screen.unrotate_xy.md)

---

Source: [Touch Simulation Module (touch)](https://xxtouch.app/en/docs/handbook/touch/index.md)
Path: handbook/touch/README.md

# Touch Simulation Module (touch)

---

- [! Tap once (touch.tap)](touch.tap.md)
- [Touch down (touch.on)](touch.on.md)
- [! Move finger on screen (:move)](touchm_move.md)
- [! Apply pressure on screen (:press)](touchm_press.md)
- [Lift finger (:off)](touchm_off.md)
- [Set movement step length (:step_len)](touchm_step_len.md)
- [Set delay per movement step (:step_delay)](touchm_step_delay.md)
- [! Millisecond sleep (:msleep)](touchm_msleep.md)
- [touch sample code](samples-1.md)

---

Source: [Key Simulation Module (key)](https://xxtouch.app/en/docs/handbook/key/index.md)
Path: handbook/key/README.md

# Key Simulation Module (key)

---

- [! Press a physical key (key.press)](key.press.md)
- [Hold down a physical key (key.down)](key.down.md)
- [Release a physical key (key.up)](key.up.md)
- [! Type text via key events (key.send_text)](key.send_text.md)
- [Input text (key.input_text)](key.input_text.md)
- [Samples and supported key codes](samples.md)

> **The following hardware keyboard functions and methods are available in versions after 20260805**

- [! Create an independent hardware keyboard (key.connect_keyboard)](key.connect_keyboard.md)
- [! Connect a global hardware keyboard (key.connect_global_keyboard)](key.connect_global_keyboard.md)
- [Get the current global hardware keyboard (key.get_global_keyboard)](key.get_global_keyboard.md)
- [Disconnect the global hardware keyboard (key.disconnect_global_keyboard)](key.disconnect_global_keyboard.md)
- [Hold down a hardware keyboard key (:down)](hardware_keyboardm_down.md)
- [Release a hardware keyboard key (:up)](hardware_keyboardm_up.md)
- [! Press a hardware keyboard key (:press)](hardware_keyboardm_press.md)
- [! Type text with a hardware keyboard (:send_text)](hardware_keyboardm_send_text.md)
- [Check whether a hardware keyboard is connected (:is_connected)](hardware_keyboardm_is_connected.md)
- [Get hardware keyboard properties (:get_properties)](hardware_keyboardm_get_properties.md)
- [Disconnect a hardware keyboard (:disconnect)](hardware_keyboardm_disconnect.md)

---

Source: [Hardware Mouse Module (mouse)](https://xxtouch.app/en/docs/handbook/mouse/index.md)
Path: handbook/mouse/README.md

# Hardware Mouse Module (mouse)

> **This module is available in versions after 20260805**

The `mouse` module creates independent hardware mouse objects. Each call to `mouse.connect` creates a new object whose button state and lifecycle are independent of every other instance.

---

- [! Create and connect a hardware mouse object (mouse.connect)](mouse.connect.md)
- [Move the hardware mouse (:move)](mousem_move.md)
- [Press a hardware mouse button (:down)](mousem_down.md)
- [Release a hardware mouse button (:up)](mousem_up.md)
- [! Click a hardware mouse button (:click)](mousem_click.md)
- [Scroll the hardware mouse wheel (:scroll)](mousem_scroll.md)
- [Get the hardware mouse connection state (:is_connected)](mousem_is_connected.md)
- [Get the hardware mouse creation properties (:get_properties)](mousem_get_properties.md)
- [Disconnect the hardware mouse (:disconnect)](mousem_disconnect.md)

---

Source: [Hardware Gamepad Module (gamepad)](https://xxtouch.app/en/docs/handbook/gamepad/index.md)
Path: handbook/gamepad/README.md

# Hardware Gamepad Module (gamepad)

> **This module is available in versions after 20260805**

The `gamepad` module creates independent gamepad objects. Each call to `gamepad.connect` creates a new object whose buttons, analog sticks, directional pad, and lifecycle are independent of every other instance.

---

- [! Create a hardware gamepad (gamepad.connect)](gamepad.connect.md)
- [Hold down a gamepad button (:down)](gamepadm_down.md)
- [Release a gamepad button (:up)](gamepadm_up.md)
- [! Press a gamepad button (:press)](gamepadm_press.md)
- [Set an analog-stick position (:set_stick)](gamepadm_set_stick.md)
- [Set the directional-pad state (:set_dpad)](gamepadm_set_dpad.md)
- [Reset gamepad state (:reset)](gamepadm_reset.md)
- [Check whether a gamepad is connected (:is_connected)](gamepadm_is_connected.md)
- [Get gamepad device properties (:get_properties)](gamepadm_get_properties.md)
- [Disconnect a hardware gamepad (:disconnect)](gamepadm_disconnect.md)

---

Source: [Text Element Module (ui_element)](https://xxtouch.app/en/docs/handbook/ui_element/index.md)
Path: handbook/ui_element/README.md

# Text Element Module (ui_element)

> **This module is available in versions after 20260507**

`ui_element` reads UI elements from the current screen by text, role, state, or coordinate, and performs actions such as click, scroll, text input, toggle, and adjustment on matched elements. It is useful when scripts need to understand the current UI, reduce hard-coded coordinates, or keep readable targeting logic across devices.

For fixed-coordinate touch operations, prefer the [Touch Module](/en/docs/handbook/touch/index.md). Coordinates exposed by `ui_element` are physical pixels.

## Basic Usage

```lua
local ui_element = require("ui_element")

local item, err = ui_element.find({
    title = "Search",
    role = "text_field",
})

if item then
    ui_element.input_text(item, "hello")
else
    sys.toast(err)
end
```

## Description

> Query APIs usually return `nil, err` on failure.
> `find_all` returns an empty array when no element matches.
> Action APIs return `true, info` on success and `nil, err` on failure.
> After the UI changes, a previous snapshot no longer represents the latest screen. Call `snapshot()` again.

---

- [Selector fields](selector.md)
- [Element fields](element.md)
- [Common options](options.md)
- [ui_element examples](samples.md)
- [List text elements (ui_element.list_text_elements)](ui_element.list_text_elements.md)
- [Get UI element at position (ui_element.text_element_at_position)](ui_element.text_element_at_position.md)
- [Find one UI element (ui_element.find)](ui_element.find.md)
- [Find multiple UI elements (ui_element.find_all)](ui_element.find_all.md)
- [Capture a UI snapshot (ui_element.snapshot)](ui_element.snapshot.md)
- [Click a UI element (ui_element.click)](ui_element.click.md)
- [Scroll a UI element or current page (ui_element.scroll)](ui_element.scroll.md)
- [Append text input (ui_element.input_text)](ui_element.input_text.md)
- [Set text content (ui_element.set_text)](ui_element.set_text.md)
- [Clear text content (ui_element.clear_text)](ui_element.clear_text.md)
- [Toggle control state (ui_element.toggle)](ui_element.toggle.md)
- [Set checked state (ui_element.set_checked)](ui_element.set_checked.md)
- [Set control value (ui_element.set_value)](ui_element.set_value.md)
- [Increase control value (ui_element.increase)](ui_element.increase.md)
- [Decrease control value (ui_element.decrease)](ui_element.decrease.md)

---

Source: [System Module (sys)](https://xxtouch.app/en/docs/handbook/sys/index.md)
Path: handbook/sys/README.md

# System Module (sys)

---

- [Show toast (sys.toast)](sys.toast.md)
- [Show system alert (sys.alert)](sys.alert.md)
- [Input prompt (sys.input_box)](sys.input_box.md)
- [Input text (sys.input_text)](sys.input_text.md)
- [! Millisecond sleep (sys.msleep)](sys.msleep.md)
- [Get current time in ms (sys.mtime)](sys.mtime.md)
- [! Get network time (sys.net_time)](sys.net_time.md)
- [Generate a random number (sys.rnd)](sys.rnd.md)
- [Get current memory info (sys.memory_info)](sys.memory_info.md)
- [Get available memory (sys.available_memory)](sys.available_memory.md)
- [Get free disk space (sys.free_disk_space)](sys.free_disk_space.md)
- [Write to system log (sys.log)](sys.log.md)
- [Send signal to pid (sys.kill)](sys.kill.md)
- [Send signal to processes by name (sys.killall)](sys.killall.md)
- [Recursively change owner (sys.lchown_r)](sys.lchown_r.md)
- [Recursively change mode (sys.lchmod_r)](sys.lchmod_r.md)
- [Recursively change owner & mode (sys.lchownmod_r)](sys.lchownmod_r.md)
- [Recursively make directories (sys.mkdir_p)](sys.mkdir_p.md)
- [Create a task (sys.task)](sys.task.md)
- [Query device information (sys.mgcopyanswer)](sys.mgcopyanswer.md)
- [Read sysctl key (sys.ctlbyname)](sys.ctlbyname.md)
- [Get system version (sys.version)](sys.version.md)
- [Get CoreFoundation version (sys.cfversion)](sys.cfversion.md)
- [Get XXTouch version (sys.xtversion)](sys.xtversion.md)
- [Get or set app tracking requests (sys.user_tracking / sys.set_user_tracking)](sys.user_tracking.md)
- [Get or set personalized ads (sys.personalized_advertising / sys.set_personalized_advertising)](sys.personalized_advertising.md)
- [Get or set location services (sys.location_services / sys.set_location_services)](sys.location_services.md)

---

Source: [Pasteboard Module (pasteboard)](https://xxtouch.app/en/docs/handbook/pasteboard/index.md)
Path: handbook/pasteboard/README.md

# Pasteboard Module (pasteboard)

---

- [Write data to pasteboard (pasteboard.write)](pasteboard.write.md)
- [Write pasteboard items (pasteboard.write_items)](pasteboard.write_items.md)
- [Read data from pasteboard (pasteboard.read)](pasteboard.read.md)
- [Clear pasteboard (pasteboard.clear)](pasteboard.clear.md)

---

Source: [Dialog Module (dialog)](https://xxtouch.app/en/docs/handbook/dialog/index.md)
Path: handbook/dialog/README.md

# Dialog Module (dialog)

By default, dialog interfaces use the webview engine.
On TrollStore builds or iOS 16+, the dialog module uses the XUI engine by default.

You can override the engine:
- `dialog.engine = "webview"` — force the webview engine
- `dialog.engine = "xui"` — force the XUI engine

---

- [! Create a dialog object (dialog)](new.md)
- [Set dialog config file name (:set_config)](dialogm_set_config.md)
- [Set dialog auto-dismiss timeout (:set_timeout)](dialogm_set_timeout.md)
- [Set dialog title (:set_title)](dialogm_set_title.md)
- [Set dialog size (:set_size)](dialogm_set_size.md)
- [Set dialog position and size (:set_frame)](dialogm_set_frame.md)
- [Set dialog corner radius (:set_corner_radius)](dialogm_set_corner_radius.md)
- [Add a text label (:add_label)](dialogm_add_label.md)
- [Add a text input (:add_input)](dialogm_add_input.md)
- [Add an image (:add_image)](dialogm_add_image.md)
- [Add a switch (:add_switch)](dialogm_add_switch.md)
- [Add a picker (:add_picker)](dialogm_add_picker.md)
- [Add a radio group (:add_radio)](dialogm_add_radio.md)
- [Add a checkbox group (:add_checkbox)](dialogm_add_checkbox.md)
- [Add a range (number selector) (:add_range)](dialogm_add_range.md)
- [! Present dialog and return user selection (:show)](dialogm_show.md)
- [! Load dialog configuration without presenting (:load)](dialogm_load.md)

---

Source: [Clear Module (clear)](https://xxtouch.app/en/docs/handbook/clear/index.md)
Path: handbook/clear/README.md

# Clear Module (clear)

---

- [Clear specific app or group keychain items (clear.keychain)](clear.keychain.md)
- [Clear all apps' keychain items (clear.all_keychain)](clear.all_keychain.md)
- [Clear browser Cookies (clear.cookies)](clear.cookies.md)
- [Clear system caches (clear.caches)](clear.caches.md)
- [Delete all local photos in Photos app (clear.all_photos)](clear.all_photos.md)
- [Clear an app's saved data (clear.app_data)](clear.app_data.md)
- [Reset IDFA/V (clear.idfav)](clear.idfav.md)

---

Source: [App Module (app)](https://xxtouch.app/en/docs/handbook/app/index.md)
Path: handbook/app/README.md

# App Module (app)

This module operates on apps via two core identifiers:

- **Bundle identifier (bid)**: the app's unique string ID, e.g. `com.tencent.mqq`; it stays the same once installed. You can look it up in `XXT App -> More -> App List`.
- **Process identifier (pid)**: the app's runtime process ID, an integer that changes with every launch.

---

- [Get app bundle path (app.bundle_path)](app.bundle_path.md)
- [Get app data path (app.data_path)](app.data_path.md)
- [Get app group info (app.group_info)](app.group_info.md)
- [Get app plugin info (app.plugin_info)](app.plugin_info.md)
- [Post an app notification (app.pop_banner)](app.pop_banner.md)
- [Run an app (app.run)](app.run.md)
- [Terminate an app (app.close)](app.close.md)
- [Simulate swipe-up quit (app.quit)](app.quit.md)
- [Check if app is running (app.is_running)](app.is_running.md)
- [Get localized name by app bundle ID (app.localized_name)](app.localized_name.md)
- [Get app icon data by bundle ID (app.png_data_for_bid)](app.png_data_for_bid.md)
- [Get pid by bundle ID (app.pid_for_bid)](app.pid_for_bid.md)
- [Get app current memory usage (app.used_memory)](app.used_memory.md)
- [Get foreground app bundle ID (app.front_bid)](app.front_bid.md)
- [Get foreground app pid (app.front_pid)](app.front_pid.md)
- [Open a URL in foreground (app.open_url)](app.open_url.md)
- [List all app bundle ids (app.bundles)](app.bundles.md)
- [Get current process list (app.all_procs)](app.all_procs.md)
- [Set app TCC permissions (app.set_tcc)](app.set_tcc.md)
- [List files opened by app (app.lsof)](app.lsof.md)
- [! Install an IPA package (app.install)](app.install.md)
- [Uninstall an app (app.uninstall)](app.uninstall.md)

---

Source: [Device Module (device)](https://xxtouch.app/en/docs/handbook/device/index.md)
Path: handbook/device/README.md

# Device Module (device)

---

- [Reset auto-lock countdown (device.reset_idle)](device.reset_idle.md)
- [Lock screen (device.lock_screen)](device.lock_screen.md)
- [Unlock screen (device.unlock_screen)](device.unlock_screen.md)
- [Get screen lock state (device.is_screen_locked)](device.is_screen_locked.md)
- [Get front app orientation (device.front_orien)](device.front_orien.md)
- [Lock device screen rotation (device.lock_orien)](device.lock_orien.md)
- [Unlock rotation lock (device.unlock_orien)](device.unlock_orien.md)
- [Get rotation lock state (device.is_orien_locked)](device.is_orien_locked.md)
- [Vibrate device (device.vibrator)](device.vibrator.md)
- [Play sound in background (device.play_sound)](device.play_sound.md)
- [Get device type (device.type)](device.type.md)
- [Get device name (device.name)](device.name.md)
- [Set device name (device.set_name)](device.set_name.md)
- [Get device UDID (device.udid)](device.udid.md)
- [Get device serial number (device.serial_number)](device.serial_number.md)
- [Get device Wi‑Fi MAC address (device.wifi_mac)](device.wifi_mac.md)
- [Get current Wi‑Fi info (device.wifi_info)](device.wifi_info.md)
- [Get all interface IPs (device.ifaddrs)](device.ifaddrs.md)
- [Get current battery level (device.battery_level)](device.battery_level.md)
- [Get current charging state (device.battery_state)](device.battery_state.md)
- [Turn on Wi‑Fi (device.turn_on_wifi)](device.turn_on_wifi.md)
- [Turn off Wi‑Fi (device.turn_off_wifi)](device.turn_off_wifi.md)
- [Turn on cellular data (device.turn_on_data)](device.turn_on_data.md)
- [Turn off cellular data (device.turn_off_data)](device.turn_off_data.md)
- [Turn on Bluetooth (device.turn_on_bluetooth)](device.turn_on_bluetooth.md)
- [Turn off Bluetooth (device.turn_off_bluetooth)](device.turn_off_bluetooth.md)
- [Turn on Airplane Mode (device.turn_on_airplane)](device.turn_on_airplane.md)
- [Turn off Airplane Mode (device.turn_off_airplane)](device.turn_off_airplane.md)
- [Connect to the selected VPN (device.turn_on_vpn)](device.turn_on_vpn.md)
- [Disconnect VPN (device.turn_off_vpn)](device.turn_off_vpn.md)
- [Check if VPN is on (device.is_vpn_on)](device.is_vpn_on.md)
- [Turn on flashlight (device.flash_on)](device.flash_on.md)
- [Turn off flashlight (device.flash_off)](device.flash_off.md)
- [Enable Reduce Motion (device.reduce_motion_on)](device.reduce_motion_on.md)
- [Disable Reduce Motion (device.reduce_motion_off)](device.reduce_motion_off.md)
- [Turn on AssistiveTouch (device.assistive_touch_on)](device.assistive_touch_on.md)
- [Turn off AssistiveTouch (device.assistive_touch_off)](device.assistive_touch_off.md)
- [Get backlight brightness (device.brightness)](device.brightness.md)
- [Set backlight brightness (device.set_brightness)](device.set_brightness.md)
- [Set auto-lock time (device.set_autolock_time)](device.set_autolock_time.md)
- [Set device volume (device.set_volume)](device.set_volume.md)
- [! Join a Wi‑Fi network (device.join_wifi)](device.join_wifi.md)
- [Forget a Wi‑Fi network (device.forget_wifi)](device.forget_wifi.md)

---

Source: [Image Object Module (image)](https://xxtouch.app/en/docs/handbook/image/index.md)
Path: handbook/image/README.md

# Image Object Module (image)

---

- [Check if a value is an image object (image.is)](image.is.md)
- [Create a blank image with size (image.new)](image.new.md)
- [Merge images (image.oper_merge)](image.oper_merge.md)
- [Create a text image (image.new_text_image)](image.new_text_image.md)
- [Load image from file (image.load_file)](image.load_file.md)
- [Load image from data (image.load_data)](image.load_data.md)
- [Copy an image object (:copy)](imagem_copy.md)
- [Crop a region from an image (:crop)](imagem_crop.md)
- [Save image to photo album (:save_to_album)](imagem_save_to_album.md)
- [Save image to PNG file (:save_to_png_file)](imagem_save_to_png_file.md)
- [Save image to JPEG file (:save_to_jpeg_file)](imagem_save_to_jpeg_file.md)
- [Get PNG data of image (:png_data)](imagem_png_data.md)
- [Get JPEG data of image (:jpeg_data)](imagem_jpeg_data.md)
- [Rotate 90° left (:turn_left)](imagem_turn_left.md)
- [Rotate 90° right (:turn_right)](imagem_turn_right.md)
- [Get image size (:size)](imagem_size.md)
- [Get color at a point (:get_color)](imagem_get_color.md)
- [Set color at a point (:set_color)](imagem_set_color.md)
- [Color replacement (:replace_color)](imagem_replace_color.md)
- [Draw image onto image (:draw_image)](imagem_draw_image.md)
- [Binarize image (:binaryzation)](imagem_binaryzation.md)
- [Multi-point color matching (:is_colors)](imagem_is_colors.md)
- [Find color in image (:find_color)](imagem_find_color.md)
- [Find subimage in image (:find_image)](imagem_find_image.md)
- [! OCR text in image (:ocr_text)](imagem_ocr_text.md)
- [Decode a QR code image (:qr_decode)](imagem_qr_decode.md)
- [Destroy an image object (:destroy)](imagem_destroy.md)
- [cv - Find image in image (:cv_find_image)](imagem_cv_find_image.md)
- [cv - Auto binarization (:cv_binaryzation)](imagem_cv_binaryzation.md)
- [cv - Resize with stretch (:cv_resize)](imagem_cv_resize.md)
- [cv - Compare images (:cv_compare_image)](imagem_cv_compare_image.md)
- [cv - Convert to shape contours (:cv_to_shapes)](imagem_cv_to_shapes.md)
- [cv - Find contours (:cv_find_shapes)](imagem_cv_find_shapes.md)
- [cv - Multi-template feature detection (:cv_detect_templates)](imagem_cv_detect_templates.md)

---

Source: [CoreML Module (coreml)](https://xxtouch.app/en/docs/handbook/coreml/index.md)
Path: handbook/coreml/README.md

# CoreML Module (coreml)

**Available since app version 1.3.8+**
The CoreML module provides on-device machine learning inference. In addition to Vision-based inference, it also includes:

- general-purpose model requests / sessions
- `MLMultiArray` creation, conversion, and math helpers
- image/tensor conversion helpers
- type-selectable text tokenizers
- generic post-processing helpers for detection / OBB / masks / keypoints / tracking

SentencePiece uses a lightweight compatibility-oriented implementation intended for on-device inference and supports both `.vocab` and `.model` sources. After `require("onnxruntime")`, native copy bridges between `MLMultiArray` and ORT tensors are also injected.

## Platform support notes

The CoreML module is based on **iOS 11+** overall, but different APIs have different minimum system requirements:

- `new_model_request` / `session`, `MLMultiArray` APIs, image tensorization, tokenizer APIs, and most geometry / post-processing helpers: **iOS 11+**
- `compile_model`, `new_vision_request`, `predict_batch()` / `run_batch()`, and `compute_units` creation/query APIs: **iOS 12+**
- Passing an `image_object` into a general-purpose model request as an image feature input: **iOS 13+**
- `class_labels()`: **iOS 14+**
- `compute_units = "cpu_and_neural_engine"`: **iOS 16+**

---

- [Compile a CoreML model](coreml.compile_model.md)
- [Create a CoreML Vision request](coreml.new_vision_request.md)
- [! Run image inference with a CoreML Vision request](coreml_vision_request_objectm_predict.md)
- [Create a general-purpose CoreML request](coreml.new_model_request.md)
- [Methods on a general-purpose CoreML request](coreml_model_request_object_methods.md)
- [ML multi-array module](coreml.multi_array_module.md)
- [Text tokenizer module](coreml.tokenizer_module.md)
- [ONNX Runtime module](../onnxruntime/README.md)

## Additional notes

- `coreml.session(...)` is an alias of `coreml.new_model_request(...)`
- `coreml.tensor(...)` is an alias of `coreml.new_multi_array(...)`
- `coreml.tensor_from_table(...)` is an alias of `coreml.multi_array_from_table(...)`
- `coreml.image_to_multi_array(...)` is still available, but it is now only a compatibility alias of `coreml.tensor_from_image(...)`
- `coreml.multi_array_from_quad(...)` is an alias of `coreml.tensor_from_quad(...)`
- `coreml.multi_array_from_quads(...)` is an alias of `coreml.tensor_from_quads(...)`
- `coreml.project_masks(...)` is an alias of `coreml.proto_masks(...)`

---

Source: [ONNX Runtime Module](https://xxtouch.app/en/docs/handbook/onnxruntime/index.md)
Path: handbook/onnxruntime/README.md

# ONNX Runtime Module

> **This module is available in versions released after 20260402**
> **Only supported on iOS 13 and later**

The `onnxruntime` module loads and runs ONNX models directly on device, suitable for text, embeddings, classification, detection, and general-purpose tensor inference workflows.

## Load the module

```lua
local ort = require("onnxruntime")
```

Unlike `coreml`, this is not a built-in global module; it is loaded on demand.

After `require("onnxruntime")` succeeds, it also injects two native copy bridges into the built-in `coreml` APIs:

- `coreml.multi_array_from_ort_tensor(tensor[, data_type])`
- `multi_array:to_ort_tensor([data_type])`

Both conversions are native-layer copies and do not go through Lua tables.

## Module-level functions

### Runtime and basic information

- `onnxruntime.version()`
- `onnxruntime.providers()`
- `onnxruntime.configure(opts)`

Notes:

- `providers()` returns the execution providers actually available in the current ORT runtime
- `configure()` sets global runtime defaults and **must be called before creating any session**

### Tensors, images, and numeric helpers

- `onnxruntime.tensor(type, shape[, data])`
- `onnxruntime.tensor_from_bytes(type, shape, bytes)`
- `onnxruntime.tensor_from_cv_mat(mat[, opts])`
- `onnxruntime.tensor_from_quad(mat, quad[, opts])`
- `onnxruntime.tensor_from_quads(mat, quads[, opts])`
- `onnxruntime.tensor_from_image(image[, opts])`
- `onnxruntime.tensor_from_images(images[, opts])`
- `onnxruntime.image_from_tensor(tensor[, opts])`
- `onnxruntime.clamp(tensor, min, max)`
- `onnxruntime.sigmoid(tensor)`
- `onnxruntime.exp(tensor)`
- `onnxruntime.where(condition, x, y)`
- `onnxruntime.matmul(lhs, rhs)`
- `onnxruntime.concat(tensors[, axis])`
- `onnxruntime.stack(tensors[, axis])`

Notes:

- `clamp()`, `sigmoid()`, `exp()`, and `matmul()` are equivalent to the same-named `tensor:` methods, with the tensor passed as the first argument
- `where()` supports mixing scalars, booleans, and tensors, and applies broadcasting rules
- Image preprocessing, OpenCV bridges, and `image_from_tensor()` details are documented in the [Tensor Module](onnxruntime.tensor_module.md)

### Detection, decoding, and post-processing helpers

- `onnxruntime.nms(boxes, scores[, opts])`
- `onnxruntime.box_points(rotated_boxes)`
- `onnxruntime.xywh_to_xyxy(boxes)`
- `onnxruntime.xyxy_to_xywh(boxes)`
- `onnxruntime.rotated_iou(lhs_box, rhs_box)`
- `onnxruntime.rotated_nms(boxes, scores[, opts])`
- `onnxruntime.create_decoder(schema)`
- `onnxruntime.decode_yolo(output[, opts])`
- `onnxruntime.decode_yolo_obb(output[, opts])`
- `onnxruntime.decode_matrix_candidates(output, schema[, opts])`
- `onnxruntime.decode_dense_detection(output, opts)`
- `onnxruntime.records_from_boxes(boxes, scores, class_ids[, keep_indices])`
- `onnxruntime.obb_records_from_rows(rows, scores, class_ids[, angles[, keep_indices[, opts]]])`
- `onnxruntime.points_to_records(points[, opts])`
- `onnxruntime.threshold_masks(masks, threshold)`
- `onnxruntime.crop_masks_by_boxes(masks, boxes)`
- `onnxruntime.resize_masks(masks, width, height[, opts])`
- `onnxruntime.mask_iou(lhs_mask, rhs_mask)`
- `onnxruntime.mask_to_polygon(mask[, opts])`
- `onnxruntime.proto_masks(proto, coeffs, boxes, image_width, image_height[, opts])`
- `onnxruntime.project_masks(proto, coeffs, boxes, image_width, image_height[, opts])`
- `onnxruntime.db_postprocess(score_map[, opts])`
- `onnxruntime.tracker([opts])`
- `onnxruntime.reshape_keypoints(points[, keypoint_count[, keypoint_dim|opts]])`
- `onnxruntime.scale_boxes(boxes, transform)`
- `onnxruntime.clip_boxes(boxes, clip_width, clip_height)`
- `onnxruntime.scale_points(points, transform[, opts])`
- `onnxruntime.scale_keypoints(points, transform[, opts])`
- `onnxruntime.clip_keypoints(points, clip_width, clip_height[, opts])`
- `onnxruntime.ctc_greedy_decode(logits[, opts])`
- `onnxruntime.sample_logits(logits[, opts])`

Notes:

- `tensor_from_quad()` / `tensor_from_quads()` require `require("image.cv")` first and are useful when OCR pipelines need to crop quadrilateral regions directly into tensors
- `box_points()` takes a rotated-box tensor shaped `[5]`, `[1, 5]`, or `[N, 5]`; it does **not** take five separate scalar arguments
- `create_decoder()` returns a decoder object with `:decode()`, `:task()`, and `:schema()`
- `tracker()` returns a tracker object with `:update()`, `:reset()`, `:state()`, and `:close()`
- `records_from_boxes()`, `obb_records_from_rows()`, and `points_to_records()` reshape tensor outputs into Lua-friendly record tables
- `proto_masks()` and `project_masks()` currently share the same implementation; `project_masks()` is an alias
- `mask_iou()` computes the intersection-over-union between two masks directly, and also accepts a third `opts` argument with `compare_size = true`, or explicit `width` / `height`
- `db_postprocess()` is intended for DB / DBNet-style text-detection post-processing; each returned detection contains `score`, `points`, and `box`
- `decode_dense_detection()` requires `opts.strides`, and it must be a non-empty array of positive integers; it also requires `decode_width` and `decode_height`, and currently supports only `box_encoding = "grid_center_log_wh"`
- `ctc_greedy_decode()` supports `blank_index`, `merge_repeated`, `apply_softmax`, `return_probabilities`, and `charset`
- `ctc_greedy_decode()` always returns `indices`; `text` appears only when `charset` is provided; `confidence` appears only when `apply_softmax` or `return_probabilities` is enabled; `probabilities` and `probability_confidence` appear only when `return_probabilities` is enabled
- `nms()` and `rotated_nms()` return `int64` tensors with **1-based** indices
- `sample_logits()` supports `argmax`, `temperature`, `top_k`, `top_p`, `min_p`, and `seed`
- `sample_logits()` returns a scalar index for 1D logits, and an `int64` tensor for batched logits

### Structured values

- `onnxruntime.value(value)`
- `onnxruntime.optional(value, type_info)`
- `onnxruntime.sequence(items)`
- `onnxruntime.map(key_type, value_type, pairs)`
- `onnxruntime.sparse_tensor(type, dense_shape, indices, values)`
- `onnxruntime.sparse_tensor_from_dense(tensor)`

These are useful when model inputs or outputs are not plain tensors — for example optionals, sequences, maps, or sparse tensors.

The current behavior can be summarized like this:

- `onnxruntime.value(x)`
  If `x` is already an ORT tensor / value / sequence / map / sparse tensor, it is returned as-is; if `x` is a Lua table, it becomes a `sequence`; otherwise the scalar is wrapped as a tensor
- `onnxruntime.optional(value, type_info)`
  The second argument is required; `type_info` may be a string or a type-info table such as the result of `session:input_info(...)` / `output_info(...)`; an empty optional is written as `onnxruntime.optional(nil, type_info)`
- `onnxruntime.map(key_type, value_type, pairs)`
  At the moment, `key_type` only supports `"string"` or `"int64"`
- `onnxruntime.sparse_tensor(type, dense_shape, indices, values)`
  Currently only numeric / `bool` sparse tensors are supported, built in COO form; `indices` may be flat or nested
- `onnxruntime.sparse_tensor_from_dense(tensor)`
  Currently does not support `string` tensors

Common object methods:

- `value:type()` / `value:has_value()` / `value:get()`
- `sequence:length()` / `sequence:get(i)` / `sequence:items()`
- `map:get(key)` / `map:set(key, value)` / `map:keys()` / `map:pairs()`
- `sparse_tensor:dense_shape()` / `sparse_tensor:values()` / `sparse_tensor:indices()` / `sparse_tensor:format()` / `sparse_tensor:to_dense()`

### Sessions and inference

- `onnxruntime.session(model_path[, opts])`
- `onnxruntime.session_from_bytes(model_bytes[, opts])`
- `onnxruntime.run_options([opts])`
- `onnxruntime.load_custom_op_library(path)`

Session objects handle model loading, input/output inspection, inference execution, and `IOBinding`. See the [Session Module](onnxruntime.session_module.md).

## Supported element types

The tensor APIs currently support these type names:

- `"float32"` / `"float"`
- `"float16"`
- `"bfloat16"`
- `"uint8"`
- `"uint16"`
- `"uint32"`
- `"uint64"`
- `"int8"`
- `"int16"`
- `"int32"`
- `"int64"`
- `"double"` / `"float64"`
- `"bool"`
- `"string"`

Notes:

- `tensor_from_bytes()` and `copy_from_bytes()` only support numeric and `bool` tensors
- `bytes()` is not available for `string` tensors
- `tensor:to("string")` currently only supports `string -> string`

## Provider notes

`onnxruntime.providers()` returns what the runtime reports as available, but the provider strings currently recognized by the session option parser are:

- `"cpu"`
- `"coreml"`

Notes:

- `provider` / `providers` also accept aliases such as `CPUExecutionProvider` and `CoreMLExecutionProvider`; they are normalized internally to `"cpu"` and `"coreml"`
- If no provider is specified, or the provider list is empty, session creation appends the CPU provider automatically
- If the provider list contains `"coreml"` and `fallback_to_cpu = true`, the implementation may also append CPU as a fallback path
- If you pass `providers = {"coreml", "cpu"}`, the session tries CoreML first and CPU second

## Working with CoreML

If you want to reuse the `coreml` tokenizer or an `MLMultiArray` preprocessing pipeline, a common pattern is:

```lua
local ort = require("onnxruntime")

local tokenizer = assert(coreml.new_text_tokenizer({
    type = "wordpiece",
    vocab_path = XXT_HOME_PATH.."/models/demo/vocab.txt",
    context_length = 52,
}))

local input_ids = assert(tokenizer:encode("hello", {
    output = "ort_tensor",
}))
```

Or convert an existing `MLMultiArray` directly into an ORT tensor:

```lua
local ort = require("onnxruntime")
local tensor = assert(multi_array:to_ort_tensor("int64"))
```

---

Source: [Process Dictionary Functions (proc)](https://xxtouch.app/en/docs/handbook/proc/index.md)
Path: handbook/proc/README.md

# Process Dictionary Functions (proc)

---

- [Store a value to process dict (proc_put)](proc_put.md)
- [Read a value from process dict (proc_get)](proc_get.md)
- [Push a value into process queue (proc_queue_push)](proc_queue_push.md)
- [Pop a value from process queue (proc_queue_pop)](proc_queue_pop.md)
- [Clear all values from process queue (proc_queue_clear)](proc_queue_clear.md)
- [Read all values from process queue (proc_queue_read)](proc_queue_read.md)
- [Get size of process queue (proc_queue_size)](proc_queue_size.md)
- [Push to front of process queue (proc_queue_push_front)](proc_queue_push_front.md)
- [Push to back of process queue (proc_queue_push_back)](proc_queue_push_back.md)
- [Pop from front of process queue (proc_queue_pop_front)](proc_queue_pop_front.md)
- [Pop from back of process queue (proc_queue_pop_back)](proc_queue_pop_back.md)
- [Pop a specific value from process queue (proc_queue_pop_value)](proc_queue_pop_value.md)
- [Count occurrences of a value in process queue (proc_queue_count_value)](proc_queue_count_value.md)
- [Run a transaction on process dict (proc_dict_run)](proc_dict_run.md)

---

Source: [Thread Module (thread)](https://xxtouch.app/en/docs/handbook/thread/index.md)
Path: handbook/thread/README.md

# Thread Module (thread)

The thread module is implemented using Lua's built-in coroutine library; it is not multi-threading in the conventional sense.

---

- [Dispatch a task (thread.dispatch)](thread.dispatch.md)
- [Get current task ID (thread.current_id)](thread.current_id.md)
- [Remove a task from the queue (thread.kill)](thread.kill.md)
- [Block and wait for another task (thread.wait)](thread.wait.md)
- [Register an event listener (thread.register_event)](thread.register_event.md)
- [Unregister an event listener (thread.unregister_event)](thread.unregister_event.md)
- [thread sample code](samples.md)

---

Source: [WebView Module (webview)](https://xxtouch.app/en/docs/handbook/webview/index.md)
Path: handbook/webview/README.md

# WebView Module (webview)

> **On iOS 16+, this module works only in TrollStore builds of XXTouch.**

---

- [Show a webview (webview.show)](webview.show.md)
- [Hide a webview (webview.hide)](webview.hide.md)
- [Execute JS on a webview (webview.eval)](webview.eval.md)
- [Get a webview's frame and hierarchy (webview.frame)](webview.frame.md)
- [Destroy a webview (webview.destroy)](webview.destroy.md)
- [webview samples](samples.md)

---

Source: [XPP Script Bundle Module (xpp)](https://xxtouch.app/en/docs/handbook/xpp/index.md)
Path: handbook/xpp/README.md

# XPP Script Bundle Module (xpp)

XPP (the “script app package”) is a bundle structure that XXTouch can parse, view, and execute. It appears as a single file with the .xpp extension, which is actually a directory bundle.

See the [XPP format](/en/docs/XPP/Layout.md) for the specification.

---

- [Get current package metadata (xpp.info)](xpp.info.md)
- [Get current package path (xpp.bundle_path)](xpp.bundle_path.md)
- [Get resource path in current package (xpp.resource_path)](xpp.resource_path.md)

---

Source: [XUI Config UI Module (xui)](https://xxtouch.app/en/docs/handbook/xui/index.md)
Path: handbook/xui/README.md

# XUI Config UI Module (xui)

XUI provides configuration UIs on XXTouch using native iOS components. This handbook specifies the layout rules for XUI. XUI is part of the [XPP Script Bundle](/en/docs/XPP/index.md) and is used to build configuration UIs for packages; it cannot be used standalone.

Refer to [XUI spec](/XUI/START.md)

---

- [Show a configuration UI (xui.show)](xui.show.md)
- [Dismiss the configuration UI (xui.dismiss)](xui.dismiss.md)
- [Validate configuration (xui.setup)](xui.setup.md)
- [Reload the current configuration UI (xui.reload)](xui.reload.md)
- [Get a value from configuration UI (xui.get)](xui.get.md)
- [Set a control's value (xui.set)](xui.set.md)
- [Read all configs in a section (xui.read)](xui.read.md)
- [Overwrite config table to a section (xui.write)](xui.write.md)
- [Clear all configs in a section (xui.clear)](xui.clear.md)

---

Source: [Extended Table Module (table)](https://xxtouch.app/en/docs/handbook/ext-table/index.md)
Path: handbook/ext-table/README.md

# Extended Table Module (table)

The [table](https://www.lua.org/manual/5.3/manual.html#6.6) module is part of Lua's standard library. XXTouch provides some extensions on top of it.

---

- [Deep copy a table (table.deep_copy)](table.deep_copy.md)
- [Deep serialize a table (table.deep_dump)](table.deep_dump.md)
- [Load a table from serialized text (table.load_string)](table.load_string.md)

---

Source: [Extended String Module (string)](https://xxtouch.app/en/docs/handbook/ext-string/index.md)
Path: handbook/ext-string/README.md

# Extended String Module (string)

The [string](https://www.lua.org/manual/5.3/manual.html#6.4) module is a Lua standard library. XXTouch extends it with additional utilities.

---

- [Convert to hex string (string.to_hex)](string.to_hex.md)
- [Convert from hex string (string.from_hex)](string.from_hex.md)
- [Convert GBK-encoded text to UTF-8 (string.from_gbk)](string.from_gbk.md)
- [Compute MD5 hash of string (string.md5)](string.md5.md)
- [Compute SHA1 hash of string (string.sha1)](string.sha1.md)
- [Compute HMAC-SHA1 hash (string.hmac_sha1)](string.hmac_sha1.md)
- [Compute HMAC-SHA256 hash (string.hmac_sha256)](string.hmac_sha256.md)
- [Base64-encode string (string.base64_encode)](string.base64_encode.md)
- [Decode Base64 string (string.base64_decode)](string.base64_decode.md)
- [Encode a URI (string.encode_uri)](string.encode_uri.md)
- [Decode a URI (string.decode_uri)](string.decode_uri.md)
- [Encode a URI component (string.encode_uri_component)](string.encode_uri_component.md)
- [Decode a URI component (string.decode_uri_component)](string.decode_uri_component.md)
- [Encrypt a string (string.aes128_encrypt)](string.aes128_encrypt.md)
- [Decrypt an encrypted string (string.aes128_decrypt)](string.aes128_decrypt.md)
- [Split string by separator pattern (string.split)](string.split.md)
- [Trim leading whitespace (string.ltrim)](string.ltrim.md)
- [Trim trailing whitespace (string.rtrim)](string.rtrim.md)
- [Trim both ends (string.trim)](string.trim.md)
- [Trim all whitespaces (string.atrim)](string.atrim.md)
- [Strip UTF-8 BOM (string.strip_utf8_bom)](string.strip_utf8_bom.md)
- [Generate a random string (string.random)](string.random.md)
- [Compare two version strings (string.compare_version)](string.compare_version.md)
- [Check if a string starts with (string.starts_with)](string.starts_with.md)
- [Check if a string ends with (string.ends_with)](string.ends_with.md)
- [Left pad (string.lpad)](string.lpad.md)
- [Right pad (string.rpad)](string.rpad.md)
- [Extended string samples](samples.md)

---

Source: [! HTTP Module (http)](https://xxtouch.app/en/docs/handbook/http/index.md)
Path: handbook/http/README.md

# ! HTTP Module (http)

This module does not support HTTP/1.0 or earlier. If your needs are not met here, you may also use the [`lcurl` module](/en/docs/handbook/open-source/lcurl.md).

---

- [Send GET request (http.get)](http.get.md)
- [Send POST request (http.post)](http.post.md)
- [Download file over HTTP (http.download)](http.download.md)
- [Send HEAD request (http.head)](http.head.md)
- [Send DELETE request (http.delete)](http.delete.md)
- [Send PUT request (http.put)](http.put.md)
- [Encode application/x-www-form-urlencoded (http.table_to_form_urlencoded)](http.table_to_form_urlencoded.md)

---

Source: [! FTP module (ftp)](https://xxtouch.app/en/docs/handbook/ftp/index.md)
Path: handbook/ftp/README.md

# ! FTP module (ftp)

---

- [FTP download (ftp.download)](ftp.download.md)
- [FTP upload (ftp.upload)](ftp.upload.md)
- [Execute an FTP command (ftp.cmd)](ftp.cmd.md)

---

Source: [JSON Module (json)](https://xxtouch.app/en/docs/handbook/json/index.md)
Path: handbook/json/README.md

# JSON Module (json)

JSON (JavaScript Object Notation) is a lightweight data-interchange format. See https://www.json.org/ for details.

This JSON module is functionally equivalent to the [LuaCJSON library](/en/docs/handbook/open-source/luacjson.md); it is not an original module.

---

- [Encode Lua value to JSON string (json.encode)](json.encode.md)
- [Decode JSON string to Lua value (json.decode)](json.decode.md)
- [NULL constant in JSON (json.null)](json.null.md)

---

Source: [PLIST Module (plist)](https://xxtouch.app/en/docs/handbook/plist/index.md)
Path: handbook/plist/README.md

# PLIST Module (plist)

---

- [Read a plist file (plist.read)](plist.read.md)
- [Write a plist file (plist.write)](plist.write.md)
- [Load plist data (plist.load)](plist.load.md)
- [Dump a Lua table to plist data (plist.dump)](plist.dump.md)
- [Convert plist data format (plist.data_convert)](plist.data_convert.md)

---

Source: [Utilities Module (utils)](https://xxtouch.app/en/docs/handbook/utils/index.md)
Path: handbook/utils/README.md

# Utilities Module (utils)

---

- [! Add one or more contacts (utils.add_contacts)](utils.add_contacts.md)
- [Remove all contacts (utils.remove_all_contacts)](utils.remove_all_contacts.md)
- [Encode text to a QR image (utils.qr_encode)](utils.qr_encode.md)
- [Get launch arguments of current script (utils.launch_args)](utils.launch_args.md)
- [Check if script is launched via App (utils.is_launch_via_app)](utils.is_launch_via_app.md)
- [Import a video to Photos (utils.video_to_album)](utils.video_to_album.md)
- [Generate a UUID (utils.gen_uuid)](utils.gen_uuid.md)
- [Generate a time-based one-time password (utils.totp_next)](utils.totp_next.md)
- [Generate a one-time password by counter (utils.hotp_counter)](utils.hotp_counter.md)
- [Generate the next counter-based one-time password (utils.hotp_next)](utils.hotp_next.md)
- [Timestamp to RFC 1123 string (utils.date_to_rfc1123)](utils.date_to_rfc1123.md)
- [RFC 1123 time string to timestamp (utils.date_from_rfc1123)](utils.date_from_rfc1123.md)
- [Timestamp to RFC 3339 string (utils.date_to_rfc3339)](utils.date_to_rfc3339.md)
- [RFC 3339 time string to timestamp (utils.date_from_rfc3339)](utils.date_from_rfc3339.md)
- [Timestamp to formatted time string (utils.date_to_format)](utils.date_to_format.md)
- [Formatted time string to timestamp (utils.date_from_format)](utils.date_from_format.md)

---

Source: [File Module (file)](https://xxtouch.app/en/docs/handbook/file/index.md)
Path: handbook/file/README.md

# File Module (file)

---

- [Check if a file or directory exists (file.exists)](file.exists.md)
- [List files in a directory (file.list)](file.list.md)
- [Get file size (file.size)](file.size.md)
- [Read all data from a file (file.reads)](file.reads.md)
- [Overwrite data to a file (file.writes)](file.writes.md)
- [Append data to a file (file.appends)](file.appends.md)
- [Count total lines in a text file (file.line_count)](file.line_count.md)
- [Get a specific line from a text file (file.get_line)](file.get_line.md)
- [Set a specific line in a text file (file.set_line)](file.set_line.md)
- [Insert content before a specific line (file.insert_line)](file.insert_line.md)
- [Remove a specific line (file.remove_line)](file.remove_line.md)
- [Get all lines from a text file (file.get_lines)](file.get_lines.md)
- [Write a sequence (array) to file line by line (file.set_lines)](file.set_lines.md)
- [Insert a sequence into file before a line (file.insert_lines)](file.insert_lines.md)
- [Get file MD5 (file.md5)](file.md5.md)
- [Get file SHA1 (file.sha1)](file.sha1.md)
- [Remove file or directory (file.remove)](file.remove.md)
- [Move file or directory (file.move)](file.move.md)
- [Copy file or directory (file.copy)](file.copy.md)
- [Find file or directory (file.find)](file.find.md)
- [Change current working directory (file.chdir)](file.chdir.md)
- [Get current working directory (file.currentdir)](file.currentdir.md)
- [Get file attributes (file.attrs)](file.attrs.md)
- [Get symlink attributes (file.lattrs)](file.lattrs.md)
- [Create a file link (file.link)](file.link.md)
- [Recursively create directories (file.mkdir_p)](file.mkdir_p.md)
- [Update access and modification time (file.touch)](file.touch.md)
- [Create a ZIP archive (file.zip)](file.zip.md)
- [Unzip a ZIP file (file.unzip)](file.unzip.md)
- [Split a path into components (file.path.components)](file.path.components.md)
- [Get the last path component (file.path.last_component)](file.path.last_component.md)
- [Remove the last path component (file.path.remove_last_component)](file.path.remove_last_component.md)
- [Append a path component (file.path.add_component)](file.path.add_component.md)
- [Get the file extension of a path (file.path.extension)](file.path.extension.md)
- [Remove the file extension from a path (file.path.remove_extension)](file.path.remove_extension.md)
- [Append a file extension (file.path.add_extension)](file.path.add_extension.md)
- [Normalize a path (file.path.normalize)](file.path.normalize.md)
- [Resolve symbolic links in a path (file.path.resolve_symlinks)](file.path.resolve_symlinks.md)

---

Source: [VPN Config Module (vpnconf)](https://xxtouch.app/en/docs/handbook/vpnconf/index.md)
Path: handbook/vpnconf/README.md

# VPN Config Module (vpnconf)

---

- [Create a VPN configuration (vpnconf.create)](vpnconf.create.md)
- [List current system VPNs (vpnconf.list)](vpnconf.list.md)
- [Select a VPN configuration (vpnconf.select)](vpnconf.select.md)
- [Delete a VPN configuration (vpnconf.delete)](vpnconf.delete.md)
- [Connect using the selected VPN (vpnconf.connect)](vpnconf.connect.md)
- [Disconnect current VPN (vpnconf.disconnect)](vpnconf.disconnect.md)
- [Get status of selected VPN (vpnconf.status)](vpnconf.status.md)

---

Source: [System Callbacks](https://xxtouch.app/en/docs/handbook/system-callback/index.md)
Path: handbook/system-callback/README.md

# System Callbacks

**No custom functions in this chapter**

---

- [Phone call in/out callback](call.md)
- [Activator event callback](activator.md)
- [HID event messages](hid.md)

---

Source: [Integrated Open-Source Libraries](https://xxtouch.app/en/docs/handbook/open-source/index.md)
Path: handbook/open-source/README.md

# Integrated Open-Source Libraries

---

- [LuaCJSON](luacjson.md)
- [LuaSocket](luasocket.md)
- [luaiconv (encoding conversion)](luaiconv.md)
- [lpeg](lpeg.md)
- [LuaFileSystem](luafilesystem.md)
- [LuaSQLite3](luasqlite3.md)
- [lcurl](lcurl.md)
- [lunix](lunix.md)
- [lua-openssl](lua-openssl.md)

---

Source: [Appendix](https://xxtouch.app/en/docs/handbook/supplement/index.md)
Path: handbook/supplement/README.md

# Appendix

---

- [Dev tools and downloads](dev-tools.md)
- [Extension libraries and remote APIs](exts.md)
- [What is Script Daemon Mode?](daemon-mode.md)
- [When auto-run at boot happens](bootstrap.md)
- [Applications of "URL Scheme"](url-scheme.md)
- [Date formatting (os.date)](os.date.md)
- [Sample code for command execution (os.execute)](os.execute.md)
- [String library samples](string-samples.md)
- [Math library samples](math-samples.md)
- [What to note when learning Lua](abc.md)
- [Common runtime errors reference](runtime-errors.md)

---

Source: [Get app bundle path (app.bundle_path)](https://xxtouch.app/en/docs/handbook/app/app.bundle_path.md)
Path: handbook/app/app.bundle_path.md

# Get app bundle path (app.bundle_path)

## Declaration

```lua
path = app.bundle_path(bid)
```

## Parameters

- bid
  String. App bundle identifier. You can find it in `XXT App -> More -> App List`.

## Returns

- path
  String | nil. The app bundle path, or nil if the app does not exist.

## Description

- Get the app's bundle path.

## Example

```lua
path = app.bundle_path("com.tencent.mqq") -- get QQ bundle path
```

---

Source: [Clear specific app or group keychain items (clear.keychain)](https://xxtouch.app/en/docs/handbook/clear/clear.keychain.md)
Path: handbook/clear/clear.keychain.md

# Clear specific app or group keychain items (clear.keychain)

## Declaration

```lua
clear.keychain(identifier)
```

## Parameters

- identifier
  String. Typically the company's reverse-domain name or the app's TeamID, e.g., `"com.doglobal"` or `"GN26HFBMX6"`.

## Description

> Clear keychain items for a specific app or group. If you are not sure what to pass, use [`clear.all_keychain`](/en/docs/handbook/clear/clear.all_keychain.md) instead.
> **WARNING:** The effect of this function is irreversible.
> **WARNING:** Do NOT pass arbitrary values; incorrect parameters may cause serious, irreversible consequences.

## Example

```lua
clear.keychain("com.doglobal") -- clear keychain items related to com.doglobal
```

---

Source: [Exit script (os.exit)](https://xxtouch.app/en/docs/handbook/control-flow/os.exit.md)
Path: handbook/control-flow/os.exit.md

# Exit script (os.exit)

## Declaration

```lua
os.exit()
```

## Description

> [`os.exit`](https://www.lua.org/manual/5.3/manual.html#pdf-os.exit) is a built-in Lua function to terminate a process. In XXTouch, it terminates the logical script process.
> Calling it in any thread will end the current script process immediately; all threads and listeners will stop at once.

## Example

```lua
os.exit()
```

---

Source: [Compile a CoreML model locally (coreml.compile_model)](https://xxtouch.app/en/docs/handbook/coreml/coreml.compile_model.md)
Path: handbook/coreml/coreml.compile_model.md

# Compile a CoreML model locally (coreml.compile_model)

## Declaration

```lua
compiled_path, err = coreml.compile_model(model_path)
```

## Parameters

- model_path
    String. Path to the model to compile. iOS 15 and later support `.mlpackage`; iOS 13, and 14 support legacy `.mlmodel` only.

    [YOLO11 to CoreML documentation](https://docs.ultralytics.com/integrations/coreml/)

    <details>
    <summary>macOS command examples for converting YOLO11 formats</summary>

    ```bash
    # Assume you already have Python 3.10. If not, create one (tested with Python 3.10 only; higher versions have not been verified)
    # Install ultralytics if needed
    pip install ultralytics

    # On iOS 13 or iOS 14, export the legacy .mlmodel format
    yolo export format=mlmodel nms=True model=best.pt

    # On iOS 15+, export the .mlpackage format
    yolo export format=coreml nms=True model=best.pt

    # nms=True is optional
    # Enable it if you want NMS baked into the exported model
    # Skip it if you plan to use coreml.nms / coreml.rotated_nms in XXTouch
    ```
    </details>

## Returns

- compiled_path
    String | nil. On success, returns the compiled model directory path; on failure, returns `nil`.

- err
    String | nil. On success, returns `nil`; on failure, returns the error message.

## Notes

- Available since app version 1.3.8+.
- Not supported on iOS versions below 12.
- This function compiles a `.mlpackage` or `.mlmodel` into a device-loadable `.mlmodelc` bundle.
- A compiled `.mlmodelc` bundle is not guaranteed to be portable across different devices or iOS versions.
    <details>

    <summary>YOLO11 training commands on an NVIDIA GPU PC</summary>

    ```bash
    # Install the Visual Studio C++ Desktop Development workload if needed
    # https://visualstudio.microsoft.com/
    # Install the CUDA 11.8 Toolkit if needed
    # https://developer.nvidia.com/cuda-11-8-0-download-archive

    # Assume Python 3.10 is available (tested with Python 3.10 only; higher versions have not been verified)
    pip install ultralytics

    # Reinstall torch builds compatible with CUDA 11.8
    pip uninstall torch torchvision torchaudio
    pip install torch torchvision torchaudio --extra-index-url https://download.pytorch.org/whl/cu118

    yolo train model=yolo11m.pt data=COCO.yml epochs=300 imgsz=640 device=0
    ```
    </details>

    <details>

    <summary>YOLO11 training commands on macOS</summary>

    ```bash
    # Assume Python 3.10 is available (tested with Python 3.10 only; higher versions have not been verified)
    pip install ultralytics

    # Install CPU/Metal torch builds
    pip install torch torchvision torchaudio

    yolo train model=yolo11m.pt data=COCO.yml epochs=300 imgsz=640 device=mps
    ```
    </details>

## Example

```lua
compiled_model_path = XXT_HOME_PATH..'/models/yolo11m.mlmodelc' -- Where to store the compiled model

file.remove(compiled_model_path) -- Always recompile during testing; comment this out once the model is stable

if not file.exists(compiled_model_path) then -- Compile if it does not exist yet
    local tmp_path, err = coreml.compile_model(XXT_HOME_PATH..'/models/yolo11m.mlpackage')
    if not tmp_path then
        error(err)
    end
    file.move(tmp_path, compiled_model_path, 'mo')
end
```

---

Source: [Print to buffer (print)](https://xxtouch.app/en/docs/handbook/develop-helper/print.md)
Path: handbook/develop-helper/print.md

# Print to buffer (print)

## Declaration

```lua
print([ arg1, arg2, ... ])
```

## Parameters

- arg1, arg2, ...
  Any type, optional, variadic. Converted to text and appended to the print buffer, separated by "\t".

## Description

> [`print`](https://www.lua.org/manual/5.3/manual.html#pdf-print) is Lua's built-in printing function. In XXTouch it prints to an internal buffer.

## Example

```lua
print("hello world")
```

---

Source: [Reset auto-lock idle timer (device.reset_idle)](https://xxtouch.app/en/docs/handbook/device/device.reset_idle.md)
Path: handbook/device/device.reset_idle.md

# Reset auto-lock idle timer (device.reset_idle)

## Declaration

```lua
device.reset_idle()
```

## Description

> Reset the auto-lock idle timer (keep screen awake)
> Avoid calling too frequently. More than 10 calls per second may crash the service or system.

## Example

```lua
-- Dispatch a task to reset idle every 29 seconds
thread.dispatch(function()
    while 1 do
        device.reset_idle()
        sys.msleep(29 * 1000)
    end
end)
```
Note: Uses functions outside this chapter [`thread.dispatch`](/en/docs/handbook/thread/thread.dispatch.md), [`sys.msleep`](/en/docs/handbook/sys/sys.msleep.md)

---

Source: [! Create a dialog object (dialog)](https://xxtouch.app/en/docs/handbook/dialog/new.md)
Path: handbook/dialog/new.md

# ! Create a dialog object (dialog)

## Declaration

```lua
dlg = dialog()
```

## Returns

- dlg
  A dialog object.

## Description

> Create a new dialog object.
> **Note** This function takes no arguments; do NOT pass any. Calling with arguments will show a popup instead, declared as:
```lua
dialog(text, timeoutSeconds)
```
> Example:
```lua
dialog('Hello, XXTouch!', 10)
```

## Example

```lua
dialog():show()
```

## Full sample

See the end of this chapter: [:show()](/en/docs/handbook/dialog/dialogm_show.md)

---

Source: [Deep copy a table (table.deep_copy)](https://xxtouch.app/en/docs/handbook/ext-table/table.deep_copy.md)
Path: handbook/ext-table/table.deep_copy.md

# Deep copy a table (table.deep_copy)

## Declaration

```lua
copied = table.deep_copy(t)
```

## Parameters

- t
  Table. The table to copy.

## Returns

- copied
  Table. A deep copy of the original table.

## Description

> Recursively copy the entire table; all values except functions and userdata are copied.
> Cyclic references in the source table are preserved in the copy.

## Example

```lua
local _g = table.deep_copy(_G)
```

---

Source: [Check if a file or directory exists (file.exists)](https://xxtouch.app/en/docs/handbook/file/file.exists.md)
Path: handbook/file/file.exists.md

# Check if a file or directory exists (file.exists)

## Declaration

```lua
exists = file.exists(path)
```

## Parameters

- path
  String. Absolute file or directory path.

## Returns

- exists
  false if the path does not exist.
  "file" if the path is a file.
  "directory" if the path is a directory.

## Description

> Determine whether a path is a file, a directory, or does not exist.

## Example

```lua
if file.exists("/var/mobile/1.zip") then
    sys.alert("/var/mobile/1.zip exists")
else
    sys.alert("/var/mobile/1.zip does not exist")
end
--
if file.exists("/var/mobile/1.zip")=="file" then
    sys.alert("/var/mobile/1.zip exists and is a file")
else
    sys.alert("/var/mobile/1.zip is not a file")
end
--
if file.exists("/var/mobile/123/")=="directory" then
    sys.alert("/var/mobile/123/ exists and is a directory")
else
    sys.alert("/var/mobile/123/ is not a directory")
end
```
**Note**: Uses [`sys.alert`](/en/docs/handbook/sys/sys.alert.md)

---

Source: [FTP download (ftp.download)](https://xxtouch.app/en/docs/handbook/ftp/ftp.download.md)
Path: handbook/ftp/ftp.download.md

# FTP download (ftp.download)

## Declaration

```lua
done, info = ftp.download(URL, localPath [, connectTimeoutSec, resumeMode, onChunk, bufferSize ])
```

## Parameters

- URL
  String. Remote file URL. Username and password are included in this parameter.
- localPath
  String. Local file path to save to.
- connectTimeoutSec
  Number, optional. Connection timeout in seconds. Default: 10.
- resumeMode
  Boolean, optional. Enable resume (breakpoint continuation) if true. Default: false.
- onChunk
  Function, optional. Callback invoked after each chunk is transferred. Default: empty function.
  The first argument is the current transfer info. If the callback returns true, the download is aborted.
- bufferSize
  Integer, optional. Buffer size in bytes. Default: auto-optimized.

## Returns

- done
  Boolean. Whether the connection/download succeeded.
- info
  Table or String. If connection succeeded, returns a table with download info; otherwise a string describing the connection failure.

## Description

```lua
-- The structure of the second return value (info) is as follows
{
    resource_size = total bytes of the remote resource,
    start_pos = start position in the resource for this download,
    size_download = bytes downloaded in this run,
    speed_download = average speed in bytes/second,
}
```
> Suitable for large file downloads; stopping the script during transfer may be slow.
> **This function may yield; other [threads](/en/docs/handbook/thread/index.md) may run before it returns.**

## Simple example

> Put credentials in the URL. Format (brackets denote optional parts):
```lua
ftp://[user:pass@]host[:port]/path
```
> If username or password contains `@`, `:`, or `/`, use `%40`, `%3A`, `%2F` respectively. For other invalid URL characters, use URL-encode.
> Example: user `havonz`, password `11@@22`
```lua
local done, info = ftp.download("ftp://havonz:11%40%4022@192.168.31.13/1.zip", "/var/mobile/1.zip")
if (done) then
    sys.alert("If nothing unexpected happened, the file has been downloaded.")
else
    sys.alert("Connection failed: "..info)
end
```

## Advanced example

```lua
local done, info = ftp.download("ftp://havonz:123456@192.168.31.13/1.zip", "/var/mobile/1.zip", 10, true, function(binfo)
    local percent = math.floor(((binfo.start_pos + binfo.size_download) / binfo.resource_size) * 100)
    sys.toast("Progress "..percent.."%")
end, 4096 * 1024)
--
if (done) then
    if (info.start_pos + info.size_download < info.resource_size) then
        sys.alert(
            "Download interrupted\nThis run "..info.size_download.." bytes"
            .."\nStarted at "..info.start_pos.." byte"
            .."\nAverage speed "..math.floor(info.speed_download/1024).." kB/s"
            .."\nRemaining "..(info.resource_size - (info.start_pos + info.size_download)).." bytes"
        )
    else
        sys.alert(
            "Download completed\nThis run "..info.size_download.." bytes"
            .."\nStarted at "..info.start_pos.." byte"
            .."\nAverage speed "..math.floor(info.speed_download/1024).." kB/s"
        )
    end
else
    sys.alert("Connection failed: "..info)
end
```
**Note**: Uses [`sys.alert`](/en/docs/handbook/sys/sys.alert.md), [`sys.toast`](/en/docs/handbook/sys/sys.toast.md)

---

Source: [! Create a hardware gamepad (gamepad.connect)](https://xxtouch.app/en/docs/handbook/gamepad/gamepad.connect.md)
Path: handbook/gamepad/gamepad.connect.md

# ! Create a hardware gamepad (gamepad.connect)

> **This function is available in versions after 20260805**

## Declaration

```lua
pad, err = gamepad.connect([properties])
```

## Parameters

- properties
  Optional table. Sets the following commonly used device properties; the values shown are used by default when omitted

```lua
{
    VendorID = 0x5858,
    ProductID = 0x0007,
    VersionNumber = 1,
    Product = "XXTouch Gamepad",
    Manufacturer = "XXTouch",
    Transport = "USB",
}
```

You may also set `SerialNumber` and `LocationID`. Other properties are not guaranteed to take effect.

## Returns

- pad
  Gamepad object or nil. A new gamepad object on success; nil if device creation fails
- err
  String. Error message when device creation fails

## Description

- Each call returns a new independent gamepad object. Input state and lifecycle are independent between objects
- The gamepad supports left and right analog sticks, a directional pad, numeric buttons `1` through `32`, and a `menu` input
- Waiting for the connection yields the current Lua execution thread
- On a system that does not support this feature, `gamepad.connect` returns `nil, error`
- A successful connection means that the gamepad object is ready to use. Whether the target app recognizes the gamepad and all of its inputs depends on the system version and the app's gamepad support
- `Transport` only affects how the local system identifies the gamepad. Setting it to `"Bluetooth"` or `"BluetoothLowEnergy"` does not create a Bluetooth connection, advertise or pair the device, or make it appear in another device's Bluetooth list

## Example

```lua
local pad, err = gamepad.connect({
    Product = "XXTouch Gamepad",
})
assert(pad, err)

assert(pad:press("a"))
assert(pad:press("menu"))
assert(pad:down("left_shoulder"))
assert(pad:set_stick("left", 0.5, 1))
assert(pad:set_dpad(1, 0))
assert(pad:up("left_shoulder"))
assert(pad:reset())

pad:disconnect()
```

---

Source: [Check if a value is an image object (image.is)](https://xxtouch.app/en/docs/handbook/image/image.is.md)
Path: handbook/image/image.is.md

# Check if a value is an image object (image.is)

## Declaration

```lua
is_image = image.is(value)
```

## Parameters

- value
  The value to test whether it is an image object

## Returns

- is_image
  Boolean. Returns true if the value is an image object; otherwise false

## Description

> Determine whether a value is an image object

## Example

```lua
if image.is(img) then
    -- img is an image object
else
    -- img is not an image object
end
```

---

Source: [! Press a physical key (key.press)](https://xxtouch.app/en/docs/handbook/key/key.press.md)
Path: handbook/key/key.press.md

# ! Press a physical key (key.press)

> **The hardware keyboard behavior described on this page is available in versions after 20260805**

## Declaration

```lua
key.press(keycode)
```

## Parameters

- keycode
  String. Physical key code. See [Samples and supported key codes](/en/docs/handbook/key/samples.md).

## Description

> Simulate pressing and then releasing a physical key.

- After a [global hardware keyboard](key.connect_global_keyboard.md) is connected, standard keyboard and keypad keys use that object. Media and vendor-defined keys keep their previous behavior
- Calls through `key(...):press()` follow the same rules
- With a global hardware keyboard, the key is held for 10 milliseconds by default and the wait may yield. Without one, behavior remains unchanged
- Failed input is not retried through the previous input method

## Example

See [the consolidated examples at the end of this chapter](/en/docs/handbook/key/samples.md).

---

Source: [! Create and connect a hardware mouse object (mouse.connect)](https://xxtouch.app/en/docs/handbook/mouse/mouse.connect.md)
Path: handbook/mouse/mouse.connect.md

# ! Create and connect a hardware mouse object (mouse.connect)

> **This function is available in versions after 20260805**


## Declaration

```lua
mouse_obj, error_message = mouse.connect([ properties ])
```


## Parameters

- properties
  Table, optional. Sets hardware mouse properties.


## Returns

- mouse_obj
  Hardware mouse object on success; `nil` if creation fails.
- error_message
  String. The reason creation failed.


## Description

> Each call creates an independent mouse object with its own button state and connection lifecycle. A successful return means that the object is ready to use; whether the target app responds still depends on iOS and the app.
> **This function yields the current Lua execution thread while waiting for the connection.**

`properties` may be omitted. The following are commonly used configurable properties and their default values:

```lua
{
    VendorID = 0x5858,
    ProductID = 0x0006,
    VersionNumber = 1,
    Product = "XXTouch Mouse",
    Manufacturer = "XXTouch",
    Transport = "USB",
}
```

> You may also set `SerialNumber` and `LocationID`. Other properties are not guaranteed to take effect.
> `Transport` only affects how iOS or the target app identifies the mouse. Setting it to `"BluetoothLowEnergy"` does not create a Bluetooth connection, advertise or pair the device, or make it appear in another device's Bluetooth list.
> If any mouse operation fails to send input, the object automatically releases all buttons and disconnects. The operation is not retried as touch input.


## Example

```lua
local m, err = mouse.connect({
    Product = "XXTouch Mouse",
})
assert(m, err)

assert(m:move(100, 0))
assert(m:down("left"))
assert(m:move(100, 50))
assert(m:up("left"))
assert(m:click("right", 60))
assert(m:click(13))
assert(m:scroll(0, 10))

m:disconnect()
```

---

Source: [ONNX Runtime Tensor Module](https://xxtouch.app/en/docs/handbook/onnxruntime/onnxruntime.tensor_module.md)
Path: handbook/onnxruntime/onnxruntime.tensor_module.md

# ONNX Runtime Tensor Module

> **This module is available in versions released after 20260402**

This page documents the most commonly used tensor-related functions and object methods in the `onnxruntime` module.

## Creation and conversion

### `onnxruntime.tensor(type, shape[, data])`

```lua
tensor, err = onnxruntime.tensor("float32", {1, 3}, {1, 2, 3})
```

Creates a regular ORT tensor.

- `type` is the element type name
- `shape` is the tensor shape
- `data` is optional; when omitted, an empty tensor is created
- Numeric tensors accept a scalar, which fills the entire tensor with the same value
- `string` tensors accept a single string, which fills the entire tensor with that same string

### `onnxruntime.tensor_from_bytes(type, shape, bytes)`

```lua
tensor, err = onnxruntime.tensor_from_bytes("float32", {1, 3}, raw_bytes)
```

Creates a tensor from contiguous raw bytes.

- Only numeric and `bool` types are supported
- The byte length must exactly match the given `shape` and `type`

### `onnxruntime.tensor_from_cv_mat(mat[, opts])`

```lua
tensor, err = onnxruntime.tensor_from_cv_mat(mat, {
    layout = "hwc",
    channel_order = "rgb",
    type = "uint8",
})
```

Converts a `cv.mat` into a tensor.

Notes:

- `require("image.cv")` first
- `opts.type` controls the target tensor element type

### `onnxruntime.tensor_from_quad(mat, quad[, opts])`

```lua
tensor, err = onnxruntime.tensor_from_quad(mat, {
    {x = 0, y = 0},
    {x = 100, y = 0},
    {x = 100, y = 32},
    {x = 0, y = 32},
}, {
    width = 100,
    height = 32,
    layout = "hwc",
    channel_order = "rgb",
    type = "uint8",
})
```

Runs a perspective crop from a `cv.mat` using a quadrilateral region and converts the result directly into an ORT tensor.

- Requires `require("image.cv")`
- `quad` may be passed directly as four points, or as a table with a `points` field
- Common `opts` mostly match `tensor_from_image()`, with extra commonly used fields such as `content_width`, `content_height`, and `border_type`
- Useful for OCR rectification plus tensorization of a single text box

### `onnxruntime.tensor_from_quads(mat, quads[, opts])`

```lua
batch_tensor, err = onnxruntime.tensor_from_quads(mat, {
    {
        points = quad1,
        content_width = 96,
        content_height = 32,
    },
    {
        points = quad2,
        content_width = 80,
        content_height = 32,
    },
}, {
    width = 96,
    height = 32,
    resize_mode = "top_left_letterbox",
    border_type = "replicate",
})
```

Runs perspective crops for multiple quadrilaterals and automatically packs the results into a batch tensor.

- Requires `require("image.cv")`
- `quads` must be a non-empty array; each item may include `points`
- Per-item `content_width` and `content_height` override the same global fields in `opts`
- The return value is packed with `stack()` or `concat()` depending on tensor rank, which is convenient for OCR batch preprocessing

### `onnxruntime.tensor_from_image(image[, opts])`

```lua
tensor, meta = onnxruntime.tensor_from_image(image, {
    width = 224,
    height = 224,
    layout = "nchw",
    channel_order = "rgb",
    data_type = "float32",
    scale = 1 / 255,
    mean = {0.485, 0.456, 0.406},
    std = {0.229, 0.224, 0.225},
    resize_mode = "letterbox",
})
```

Converts an image object directly into an ONNX Runtime input tensor.

Common options:

- `width` / `height`
- `layout`: `"nchw"`, `"nhwc"`, `"chw"`, or `"hwc"`
- `channel_order`: `"rgb"`, `"bgr"`, `"gray"`, `"grey"`, or `"grayscale"`
- `data_type`
- `scale`
- `mean`
- `std`
- `resize_mode`: `"stretch"`, `"letterbox"`, or `"center_crop"`
- `letterbox_mode`: supports `"top_left"`; otherwise letterboxing is centered
- `pad_color`
- `interpolation`: `"bilinear"` or `"nearest"`
- `alpha_mode`: `"ignore"`, `"white"`, `"black"`, or `"premultiply"`
- `crop = {x, y, width, height}`
- `add_batch`

On success, the second return value is a preprocessing metadata table. Common fields include:

- `src_width` / `src_height`
- `crop_x` / `crop_y` / `crop_width` / `crop_height`
- `dst_width` / `dst_height`
- `resized_width` / `resized_height`
- `layout`
- `channel_order`
- `resize_mode`
- `scale_x` / `scale_y` / `ratio`
- `offset_x` / `offset_y`
- `pad_left` / `pad_top` / `pad_right` / `pad_bottom`

### `onnxruntime.tensor_from_images(images[, opts])`

```lua
batch_tensor, metas = onnxruntime.tensor_from_images({img1, img2}, {
    width = 640,
    height = 640,
    layout = "nchw",
})
```

Converts a batch of images into a tensor.

- Source image sizes may differ
- The batch can be formed as long as each image resolves to the same output shape and `data_type`
- The second return value is a metadata array aligned with the input order

### `onnxruntime.image_from_tensor(tensor[, opts])`

```lua
image, err = onnxruntime.image_from_tensor(tensor, {
    layout = "nchw",
    channel_order = "rgb",
    batch_index = 1,
    scale = 1 / 255,
    mean = {0.485, 0.456, 0.406},
    std = {0.229, 0.224, 0.225},
    value_range = "0_1",
})
```

Converts a 2D / 3D / 4D tensor back into an image object. Useful for debugging model inputs and outputs.

Common options:

- `layout`
- `channel_order`
- `batch_index`: **1-based**, default `1`
- `scale`
- `mean`
- `std`
- `clamp`
- `value_range`: `"0_255"` or `"0_1"`

Notes:

- Only 2D / 3D / 4D tensors are supported
- The channel count must be `1` or `3`

## Tensor object methods

### Basic information

- `tensor:shape()`
- `tensor:rank()`
- `tensor:size()`
- `tensor:type()`
- `tensor:to_table()`
- `tensor:bytes()`

Notes:

- `to_table()` expands the tensor contents into a Lua table
- `bytes()` only supports numeric and `bool` tensors

### Read, write, and copy

- `tensor:get(index1[, index2, ...])`
- `tensor:set(index1[, index2, ...], value)`
- `tensor:fill(value_or_table)`
- `tensor:clone()`
- `tensor:copy_from_bytes(raw_bytes)`
- `tensor:to(type)`

Notes:

- `fill()` accepts either a scalar fill value or a Lua table whose element count must match exactly
- `copy_from_bytes()` only supports numeric and `bool` tensors, and the byte length must match exactly
- `get()` / `set()` use **1-based** indexing semantics
- `tensor:to("string")` currently only supports `string -> string`

### Shape and indexing

- `tensor:reshape(shape)`
- `tensor:transpose([axes])`
- `tensor:flatten([start_dim[, end_dim]])`
- `tensor:squeeze([dim])`
- `tensor:unsqueeze(dim)`
- `tensor:slice(dim, start, stop[, step])`
- `tensor:select(dim, index)`
- `tensor:gather(dim, indices)`

Notes:

- `slice()` uses **1-based** `start` and `stop`, and `stop` is inclusive
- `slice()` requires a positive `step`
- `select()` removes the selected dimension
- `gather()` accepts either a Lua array or a shape-`[N]` tensor as `indices`, still using **1-based** indexing semantics
- These methods return new tensor objects

### Numeric operations

- `tensor:add(other)`
- `tensor:sub(other)`
- `tensor:mul(other)`
- `tensor:div(other)`
- `tensor:clamp(min, max)`
- `tensor:sigmoid()`
- `tensor:exp()`
- `tensor:matmul(other)`
- `tensor:dot(other)`

Notes:

- `other` can be a scalar or another tensor with a matching shape
- `matmul()` currently supports rank-1 / rank-2 tensor combinations
- `sigmoid()`, `exp()`, and `matmul()` promote results to a floating-point result type
- These operations do not support `string` tensors

### Reductions, sorting, and probability

- `tensor:argmax([axis])`
- `tensor:sum([axis])`
- `tensor:mean([axis])`
- `tensor:max([axis])`
- `tensor:min([axis])`
- `tensor:softmax([axis])`
- `tensor:normalize([axis])`
- `tensor:sort([axis[, descending]])`
- `tensor:topk(k[, axis])`

Notes:

- `argmax()` without an axis returns a single **1-based** index
- `argmax(axis)` returns an `int64` tensor, also with **1-based** indices
- `sort()` returns `{ values = tensor, indices = tensor }`
- `topk()` returns `{ values = tensor, indices = tensor }`
- `sort()` and `topk()` both return **1-based** indices

### OpenCV bridge

- `tensor:to_cv_mat([opts])`

```lua
mat, err = tensor:to_cv_mat({
    layout = "hwc",
    channel_order = "rgb",
    coreml_data_type = "uint8",
})
```

Notes:

- `require("image.cv")` first
- Some tensor types cannot be mapped to `cv.mat` directly; in those cases pass `coreml_data_type` explicitly

## Module-level tensor helpers

### Basic numeric helpers

- `onnxruntime.clamp(tensor, min, max)`
- `onnxruntime.sigmoid(tensor)`
- `onnxruntime.exp(tensor)`
- `onnxruntime.where(condition, x, y)`
- `onnxruntime.matmul(lhs, rhs)`
- `onnxruntime.concat(tensors[, axis])`
- `onnxruntime.stack(tensors[, axis])`

Notes:

- `clamp()`, `sigmoid()`, `exp()`, and `matmul()` share the same implementation as the corresponding `tensor:` methods
- `where()` supports scalar / boolean / tensor mixtures and follows broadcasting rules

### Additional post-processing helpers

- `onnxruntime.mask_iou(lhs_mask, rhs_mask)`
- `onnxruntime.db_postprocess(score_map[, opts])`

Notes:

- `mask_iou()` computes the intersection-over-union between two masks directly
- `mask_iou()` also accepts a third `opts` argument with `compare_size = true`, or explicit `width` / `height` for the comparison size
- `db_postprocess()` is intended for DB / DBNet-style text-detection post-processing; inputs may be `[H, W]`, `[C, H, W]`, or `[N, C, H, W]`
- `db_postprocess()` returns a detection array where each item contains `score`, `points`, and `box`; `meta` / `image_meta` can reuse preprocessing metadata returned by image tensorization

### `onnxruntime.nms(boxes, scores[, opts])`

Axis-aligned box NMS.

Common options:

- `iou_threshold`
- `score_threshold`
- `top_k`
- `class_aware`
- `class_ids`

Returns an `int64` tensor with **1-based** indices.

### `onnxruntime.box_points(rotated_boxes)`

Converts rotated boxes `[cx, cy, w, h, theta]` into four corner points.

- The input may be a tensor shaped `[5]`, `[1, 5]`, or `[N, 5]`
- A single box returns one Lua point list; multiple boxes return an array of point lists

### `onnxruntime.xywh_to_xyxy(boxes)`

Converts boxes from `[cx, cy, w, h]` to `[x1, y1, x2, y2]`.

### `onnxruntime.xyxy_to_xywh(boxes)`

Converts boxes from `[x1, y1, x2, y2]` to `[cx, cy, w, h]`.

### `onnxruntime.rotated_iou(box1, box2)`

Computes IoU between two rotated boxes.

### `onnxruntime.rotated_nms(boxes, scores[, opts])`

Rotated-box NMS. The return value is also an `int64` tensor with **1-based** indices.

- `boxes` must be shaped `[N, 5]`
- `scores` may be a Lua numeric array or a tensor shaped `[N]` / `[N, 1]`

### `onnxruntime.create_decoder(schema)`

Creates a reusable decoder object.

- Decoder objects support `:decode(output[, opts])`, `:task()`, and `:schema()`
- This is useful when a detection / OBB / classification schema should be defined once and reused

### `onnxruntime.decode_yolo(output[, opts])`

Decodes output with the built-in YOLO detection path and returns detection records.

### `onnxruntime.decode_yolo_obb(output[, opts])`

Decodes output with the built-in YOLO OBB path and returns rotated detection records.

### `onnxruntime.decode_matrix_candidates(output, schema[, opts])`

Splits a matrix output into candidate tensors according to a schema. The returned table commonly contains:

- `boxes`
- `scores`
- `class_ids`
- `keep_indices`
- `selected_rows`
- `angles` (for OBB-related schemas)

### `onnxruntime.decode_dense_detection(output, opts)`

Decodes a dense detection head output into:

- `boxes`
- `scores`
- `labels`

All three fields are tensors.

- Inputs may be shaped `[R, C]` or `[N, R, C]`
- `opts.strides` is required, and it must be a non-empty array of positive integers
- `decode_width` and `decode_height` are also required
- Currently only `box_encoding = "grid_center_log_wh"` is supported
- Other common fields include `box_offset`, `score_offset`, `class_offset`, `num_classes`, and `score_threshold`
- Batched outputs return a Lua array of per-batch results

### `onnxruntime.records_from_boxes(boxes, scores, class_ids[, keep_indices])`

Turns `[N, 4]` boxes, scores, and class IDs into Lua record tables. Each record commonly includes:

- `box`
- `score`
- `class_id`
- `row_index`
- `x1` / `y1` / `x2` / `y2`
- `width` / `height`
- `cx` / `cy`

### `onnxruntime.obb_records_from_rows(rows, scores, class_ids[, angles[, keep_indices[, opts]]])`

Turns OBB row tensors into Lua record tables.

- `opts` supports `x_index`, `y_index`, `width_index`, and `height_index`

### `onnxruntime.points_to_records(points[, opts])`

Turns `[N, P, D]` or `[N, P*D]` point / keypoint tensors into Lua tables.

- `opts` supports `point_count` / `keypoint_count`
- `opts` supports `point_dim` / `keypoint_dim`

### Mask helpers

#### `onnxruntime.threshold_masks(masks, threshold)`

Thresholds dense mask tensors into Lua mask tables. Each mask contains:

- `width`
- `height`
- `bits`
- `pixel_count`
- `bounds`

#### `onnxruntime.crop_masks_by_boxes(masks, boxes)`

Crops thresholded mask tables using `[N, 4]` boxes.

#### `onnxruntime.resize_masks(masks, width, height[, opts])`

Resizes mask tables to a target size.

- Only `opts.interpolation = "nearest"` is currently supported

#### `onnxruntime.mask_to_polygon(mask[, opts])`

Converts one binary mask into a polygon point list.

- `opts.epsilon` / `opts.approx_epsilon` can be used for polygon simplification

#### `onnxruntime.proto_masks(proto, coeffs, boxes, image_width, image_height[, opts])`

Projects prototype masks, mask coefficients, and detection boxes back into the target image size.

- `project_masks()` is an alias
- The return value is a Lua mask-table list, not a tensor

### Keypoint and geometry helpers

- `onnxruntime.reshape_keypoints(points[, keypoint_count[, keypoint_dim|opts]])`
- `onnxruntime.scale_boxes(boxes, transform)`
- `onnxruntime.clip_boxes(boxes, clip_width, clip_height)`
- `onnxruntime.scale_points(points, transform[, opts])`
- `onnxruntime.scale_keypoints(points, transform[, opts])`
- `onnxruntime.clip_keypoints(points, clip_width, clip_height[, opts])`

Notes:

- `reshape_keypoints()` reshapes between `[N, K*D]` and `[N, K, D]`
- `scale_points()` assumes a generic point layout by default; `scale_keypoints()` assumes a keypoint layout by default
- Transform tables align with image preprocessing metadata fields such as `scale_x`, `scale_y`, `pad_left`, and `pad_top`

### `onnxruntime.tracker([opts])`

Creates a reusable tracker object with:

- `tracker:update(detections[, timestamp])`
- `tracker:reset()`
- `tracker:state()`
- `tracker:close()`

Common config fields:

- `iou_threshold`
- `max_age`
- `min_hits`

### `onnxruntime.ctc_greedy_decode(logits[, opts])`

Returns a table like:

- `indices`
- `text`
- `confidence`

- Inputs may be shaped `[T, C]` or `[N, T, C]`
- Supports `blank_index`, `merge_repeated`, `apply_softmax`, `return_probabilities`, and `charset`
- Always returns `indices`
- `text` appears only when `charset` is provided
- `confidence` appears only when `apply_softmax` or `return_probabilities` is enabled
- `probabilities` and `probability_confidence` appear only when `return_probabilities` is enabled
- Batched inputs return an array of per-batch decode results

### `onnxruntime.sample_logits(logits[, opts])`

Supports these sampling options:

- `argmax`
- `temperature`
- `top_k`
- `top_p`
- `min_p`
- `seed`

For 1D logits it returns a scalar index. For batched logits it returns an `int64` tensor. Indices are **1-based**.

## Example

```lua
local ort = require("onnxruntime")

local tensor = assert(ort.tensor("float32", {2, 3}, {
    1, 9, 3,
    8, 2, 7,
}))

local sliced = assert(tensor:slice(2, 2, 3))
print(sliced:to_table()[1]) -- 9

local topk = assert(tensor:topk(2, 2))
print(topk.values:to_table()[1])  -- 9
print(topk.indices:to_table()[1]) -- 2
```

---

Source: [LuaCJSON Library](https://xxtouch.app/en/docs/handbook/open-source/luacjson.md)
Path: handbook/open-source/luacjson.md

# LuaCJSON Library

[LuaCJSON manual](https://kyne.au/~mark/software/lua-cjson-manual.html)

Note: XXTouch's built-in JSON module is LuaCJSON, see [JSON module (json)](/en/docs/handbook/json/index.md)

---

---

Source: [Write data to pasteboard (pasteboard.write)](https://xxtouch.app/en/docs/handbook/pasteboard/pasteboard.write.md)
Path: handbook/pasteboard/pasteboard.write.md

# Write data to pasteboard (pasteboard.write)

## Declaration

```lua
pasteboard.write(data [, uti ])
pasteboard.write(item [, options ])
pasteboard.write(items [, options ])
```

## Parameters

- data
  String. The content to write to the system pasteboard.
  Table. A pasteboard item whose keys are UTIs and values are string data. (supported since version 20260428)
  Table. A list of pasteboard items. (supported since version 20260428)
- uti
  String, optional. [Uniform Type Identifiers](https://developer.apple.com/library/ios/documentation/Miscellaneous/Reference/UTIRef/Articles/System-DeclaredUniformTypeIdentifiers.html). Default: "public.utf8-plain-text".
- options
  Table, optional. (supported since version 20260428)
  `local_only`: Boolean. Keep the content local to this device. Supported on iOS 10 and later.
  `expiration_date`: Number. Unix timestamp in seconds. Supported on iOS 10 and later.

  <details>
  <summary>Pasteboard item structure</summary>

  ```lua
  {
      ["public.utf8-plain-text"] = "plain text",
      ["public.rtf"] = "RTF data",
      ["public.html"] = "HTML data",
      ["public.png"] = "PNG binary data",
      ...
  }
  ```
  </details>

## Returns

- success
  Boolean. Returns `true` when writing succeeds; otherwise returns `false`.

## Description

> Write content into the system pasteboard.
> When `item` or `items` is provided, multiple representations are written to the same pasteboard item. iOS 9 ignores `options`.

## Example

```lua
pasteboard.write("hello") -- Write the text "hello" to the pasteboard
--
pasteboard.write(screen.image():png_data(), 'public.png') -- Write a screenshot to the pasteboard
--
pasteboard.write([[{\rtf1\ansi\deff0
{\fonttbl{\f0 Helvetica;}}
{\colortbl;\red255\green0\blue0;}
\f0\fs32 normal {\b bold} {\i italic} \cf1 red\cf0\par
\u20320?\u22909?
}]], "public.rtf") -- Write RTF rich text to the pasteboard

-- Version 20260428 and later support writing multiple representations to one item
pasteboard.write({
    ["public.utf8-plain-text"] = "normal bold italic red\nHello",
    ["public.rtf"] = [[{\rtf1\ansi\deff0
{\fonttbl{\f0 Helvetica;}}
{\colortbl;\red255\green0\blue0;}
\f0\fs32 normal {\b bold} {\i italic} \cf1 red\cf0\par
Hello
}]],
    ["public.html"] = [[<p>normal <b>bold</b> <i>italic</i> <span style="color:red">red</span><br>Hello</p>]],
}, {
    local_only = true,
    expiration_date = os.time() + 3600,
})
```
**Note**: Uses [`screen.image`](/en/docs/handbook/screen/screen.image.md)

---

Source: [Read a plist file (plist.read)](https://xxtouch.app/en/docs/handbook/plist/plist.read.md)
Path: handbook/plist/plist.read.md

# Read a plist file (plist.read)

## Declaration

```lua
tab = plist.read(filePath)
```

## Parameters

- filePath
  String. Absolute path of the plist file to read.

## Returns

- tab
  Table or nil. On success, returns a table representing the plist tree; otherwise nil.

## Description

> Read a plist file and convert it to a Lua table.
> Non-generic data types in plist are not supported and will be ignored.
> This function can be used in XUI.

## Example

```lua
local plist = require("plist")
local plfilename = "/var/mobile/Library/Caches/com.apple.mobile.installation.plist"
local tmp2 = plist.read(plfilename)
sys.alert(tmp2['Metadata']['ProductBuildVersion'])
```
**Note**: Uses [`sys.alert`](/en/docs/handbook/sys/sys.alert.md)

---

Source: [Store a value to process dict (proc_put)](https://xxtouch.app/en/docs/handbook/proc/proc_put.md)
Path: handbook/proc/proc_put.md

# Store a value to process dict (proc_put)

## Declaration

```lua
old_value = proc_put(key, new_value)
```

## Parameters

- key
  String.
- new_value
  String. The value to set.

## Returns

- old_value
  String. Returns the old value at this key. If none existed, returns an empty string.

## Description

- All process dict entries whose keys start with "xxtouch." or "1ferver." are reserved.
- Store a value into the process dictionary and return the previous value.
- If the key had no previous value, an empty string is returned.
- Storing an empty string clears the value for this key.

## Example

```lua
local bill = ""
while bill == "" do
    bill = proc_put("billno", "")
end
print("billno: ".. bill)
```

---

Source: [Initialize the Rotated Coordinate System (screen.init)](https://xxtouch.app/en/docs/handbook/screen/screen.init.md)
Path: handbook/screen/screen.init.md

# Initialize the Rotated Coordinate System (screen.init)

## Declaration

```lua
previousCoordinateSystem = screen.init(orientation)
```

## Parameters

- orientation
    Integer value.
    0 means portrait with Home at the bottom
    1 means landscape with Home on the right
    2 means landscape with Home on the left
    3 means portrait with Home at the top

## Returns

- previousCoordinateSystem
    Integer value that represents the coordinate system in use before this call.


## Description

Initializes the coordinate system used when sampling colors or performing touch actions.
This setting affects how coordinate parameters and return values are interpreted by the following functions:
```
screen.get_color
screen.is_colors
screen.find_color
screen.ocr_text
screen.image
touch.on
touch.move
touch.off
touch.tap
```

Using an iPhone 8 as the example (750x1334 resolution):

<details>

<summary>Default portrait coordinate system, screen.init(0)</summary>

```
(0,0) physical top-left corner
┌──────────────────────────────────▶ x+
│                                  │
│
│                                  │
│
│                                  │
│
│                                  │
│
│                                  │
│
│                                  │
│
│                                  │
│
│                                  │
│
│                                  │
│
▼ y+                               ▼
                                (750,1334) physical bottom-right corner
┌──────────────────────────────────┐
│               Home               │
└──────────────────────────────────┘
```
</details>


<details>

<summary>Landscape with Home on the right, screen.init(1)</summary>

```
 (0,0)
   ┌────────────────────────────────────────────────▶ x+ physical bottom-right corner
   │                                                 │   ┌───┐
   │                                                     │   │
   │                                                 │   │   │
   │                                                     │   │
   │                                                 │   │   │
   │                                                     │ H │
   │                                                 │   │ o │
   │                                                     │ m │
   │                                                 │   │ e │
   │                                                     │   │
   │                                                 │   │   │
   │                                                     │   │
   │                                                 │   │   │
   │                                                 │   └───┘
   ▼ y+                                              ▼
physical top-left corner                           (1334,750)
```
</details>


<details>

<summary>Landscape with Home on the left, screen.init(2)</summary>

```
      (0,0)
        ┌────────────────────────────────────────────────▶ x+ physical top-left corner
┌───┐   │                                                 │
│   │   │
│   │   │                                                 │
│   │   │
│   │   │                                                 │
│ H │   │
│ o │   │                                                 │
│ m │   │
│ e │   │                                                 │
│   │   │
│   │   │                                                 │
│   │   │
│   │   │                                                 │
└───┘   │                                                 │
        ▼ y+                                              ▼
     physical bottom-right corner                      (1334,750)
```
</details>


<details>

<summary>Portrait with Home at the top, screen.init(3)</summary>

```
   ┌──────────────────────────────────┐
   │               Home               │
   └──────────────────────────────────┘
 (0,0) physical bottom-right corner
   ┌──────────────────────────────────▶ x+
   │                                  │
   │
   │                                  │
   │
   │                                  │
   │
   │                                  │
   │
   │                                  │
   │
   │                                  │
   │
   │                                  │
   │
   │                                  │
   │
   │                                  │
   │
   ▼ y+                               ▼
                                  (750,1334) physical top-left corner
```
</details>


## Example

```lua
screen.init(0)    -- Home at the bottom
screen.init(1)    -- Home on the right
screen.init(2)    -- Home on the left
screen.init(3)    -- Home at the top
```

The following aliases have the same effect:
```lua
screen.init_home_on_bottom()    -- Home at the bottom
screen.init_home_on_right()     -- Home on the right
screen.init_home_on_left()      -- Home on the left
screen.init_home_on_top()       -- Home at the top
```

---

Source: [Developer & Companion Tool Downloads](https://xxtouch.app/en/docs/handbook/supplement/dev-tools.md)
Path: handbook/supplement/dev-tools.md

# Developer & Companion Tool Downloads

> - [Install XXTouch Script Assistant in VSCode](vscode:extension/xxtouch.xxtouch)
>     - Download VSCode here: https://code.visualstudio.com/
> - [Install XXTouch Script Assistant in Cursor](cursor:extension/xxtouch.xxtouch)
>     - Download Cursor here: https://cursor.sh/
> - [Install XXTouch Script Assistant in Devin](devin:extension/xxtouch.xxtouch)
>     - Download Devin here: https://devin.ai/desktop
> - [Install XXTouch Script Assistant in Qoder](qoder:extension/xxtouch.xxtouch)
>     - Download Qoder here: https://qoder.com/ide
> - [Install XXTouch Script Assistant in TRAE](trae:extension/xxtouch.xxtouch)
>     - Download TRAE here: https://trae.ai/ide
> - [Download XXTouch Script Assistant .vsix](https://marketplace.visualstudio.com/_apis/public/gallery/publishers/xxtouch/vsextensions/xxtouch/latest/vspackage)


---

> - [XXTLanControl](https://xxtlc-releases.xxtouch.app/en/) (includes MCP and Skills, and integrates a lightweight development environment)

---

> - [XXTCloudControl](https://xxtccc-releases.xxtouch.app/en/) (open-source self-hosted)

---

## Legacy Tools

> - [XXTColorPicker for Windows](http://xxt-dist.xxtouch.app/XXTColorPicker/XXTColorPicker%201.0.36%20For%20Windows.7z)
> - [XXTColorPicker for macOS](http://xxt-dist.xxtouch.app/XXTColorPicker/XXTColorPicker%201.0.36%20For%20macOS%20(depends%20JRE).zip)

---

> - [XXTStudio for Windows](http://xxt-dist.xxtouch.app/XXTStudio/XXTStudio-Win-2026091115.zip)
> - [XXTStudio for macOS](http://xxt-dist.xxtouch.app/XXTStudio/XXTStudio-macOS-2026091115.zip)

---

Source: [Show Toast (sys.toast)](https://xxtouch.app/en/docs/handbook/sys/sys.toast.md)
Path: handbook/sys/sys.toast.md

# Show Toast (sys.toast)

## Declaration

```lua
sys.toast(text [, orientation ])
```

## Parameters

- text
  String. The message to display.
- orientation
  Integer, optional. Screen orientation. Defaults to the last orientation set by [`screen.init`](/en/docs/handbook/screen/screen.init.md).
  `0` = portrait (Home at bottom)
  `1` = landscape (Home at right)
  `2` = landscape (Home at left)
  `3` = portrait (Home at top)
  `-1` = hide toast immediately

## Description

> Displays a toast message at the bottom of the screen in the current rotated coordinate system.
> **This function is asynchronous. The toast is shown for a total of 2.8 seconds and does not block taps.**
> **On iOS 13.2+, it does not affect color picking.**

## Example

```lua
-- Show a toast
sys.toast("Hello world!")
```

## Example

```lua
-- Show current date & time in real time
while (true) do
    sys.toast("Long press volume key to stop by default\n\n"..os.date("%Y-%m-%d %H:%M:%S"), device.front_orien())
    sys.msleep(1000)
end
```
**Note**: The above uses functions outside this chapter: [`device.front_orien`](/en/docs/handbook/device/device.front_orien.md), [`os.date`](/en/docs/handbook/supplement/os.date.md)

---

Source: [Incoming/outgoing call callback](https://xxtouch.app/en/docs/handbook/system-callback/call.md)
Path: handbook/system-callback/call.md

# Incoming/outgoing call callback

## Declaration

```lua
thread.register_event("xxtouch.call_callback", function(val)
    if (val == "in") then
        -- incoming call
    elseif (val == "out") then
        -- outgoing call
    elseif (val == "disconnected") then
        -- call disconnected
    end
end)
```

## States

- in
  When an incoming call arrives, the process queue dictionary identified by xxtouch.call_callback receives this value.
- out
  When a call is dialed out, the process queue dictionary identified by xxtouch.call_callback receives this value.
- disconnected
  When an incoming or outgoing call ends, the process queue dictionary identified by xxtouch.call_callback receives this value.

## Description

> When the system receives an incoming or outgoing call event, a state is pushed into the process queue dictionary identified by this message.

## Example

```lua
-- Clear message queue
proc_queue_clear("xxtouch.call_callback")
--
sys.toast("The script will now listen for call events and stop after 20 seconds")
--
-- Start listening
local eid = thread.register_event("xxtouch.call_callback", function(val)
    if (val == "in") then
        sys.toast("Incoming call")
    elseif (val == "out") then
        sys.toast("Outgoing call")
    elseif (val == "disconnected") then
        sys.toast("Call disconnected")
    end
end)
--
sys.msleep(20000) -- wait 20 seconds
--
-- Unregister callback; without unregistering, the script will not end here
thread.unregister_event("xxtouch.call_callback", eid)
```
**Note**: Uses [`sys.toast`](/en/docs/handbook/sys/sys.toast.md), [`sys.msleep`](/en/docs/handbook/sys/sys.msleep.md), [`proc_queue_clear`](/en/docs/handbook/proc/proc_queue_clear.md), [`thread.register_event`](/en/docs/handbook/thread/thread.register_event.md), [`thread.unregister_event`](/en/docs/handbook/thread/thread.unregister_event.md)

---

Source: [Dispatch a task (thread.dispatch)](https://xxtouch.app/en/docs/handbook/thread/thread.dispatch.md)
Path: handbook/thread/thread.dispatch.md

# Dispatch a task (thread.dispatch)

## Declaration

```lua
task_id = thread.dispatch(task [, on_error ])
```

## Parameters

- task
  Function. The function to be enqueued as a task.
- on_error
  Function. Optional error callback. If the task throws, this callback will be invoked and no error is rethrown. Default: throw on error.

## Returns

- task_id
  Integer.

## Description

Dispatch a task to the queue. It will start running as soon as the scheduler is idle.

## Example

See [the consolidated examples at the end of this chapter](/en/docs/handbook/thread/samples.md)

---

Source: [! Tap Once (touch.tap)](https://xxtouch.app/en/docs/handbook/touch/touch.tap.md)
Path: handbook/touch/touch.tap.md

# ! Tap Once (touch.tap)

## Declaration

```lua
touch.tap(x, y [, holdMs, waitAfterMs ])
```

## Parameters

- x, y
  Integers. Coordinates of the tap point in the current rotated coordinate system.
- holdMs
  Integer, optional. Time between touch down and lift up in milliseconds. Default: 30.
- waitAfterMs
  Integer, optional. Extra wait time after the tap finishes in milliseconds. Default: 0.

## Description

> Simulates a single tap at the specified position.
> **This call may yield; other [threads](/en/docs/handbook/thread/index.md) may run before it returns.**
> **Note:** During the call, a finger id is allocated and occupied automatically. The pool size is limited (about 30). If you exceed the limit and call [touch.on](/en/docs/handbook/touch/touch.on.md) or [touch.tap](/en/docs/handbook/touch/touch.tap.md) again, a `finger pool overflow` error will be thrown. Avoid **simultaneously** occupying too many finger ids, and release them promptly with `:off`.

## Example

```lua
touch.tap(100, 100) -- tap position 100,100

touch.tap(100, 100, 300) -- press at 100,100, hold 0.3s, then lift

touch.tap(100, 100, 300, 1000) -- press 0.3s, lift, then wait 1s more
```

---

Source: [Selector Fields](https://xxtouch.app/en/docs/handbook/ui_element/selector.md)
Path: handbook/ui_element/selector.md

# Selector Fields

> **This module is available in versions after 20260507**

A selector is a Lua table that describes the UI element to find or operate on. Prefer readable text plus role, and add `index` only when several elements look the same.

## Example

```lua
local selector = {
    title = "Search",
    role = "text_field",
}

local item = ui_element.find(selector)
```

## Fields

- title / text
  String. Match the element's readable title. These two fields have the same meaning.
- text_contains
  String. Match a substring in the readable title.
- value
  String, number, or boolean. Match the element's current value.
- value_contains
  String. Match a substring in the element value.
- identifier
  String. Match the element identifier. Not every app provides it.
- bundle_id
  String. Match the bundle identifier of the app that owns the element.
- role
  String. Match the element type. Common values include `button`, `text_field`, `static_text`, `switch`, `checkbox`, `radio`, `slider`, `picker`, `scrollable`, `link`, `image`, `keyboard_key`.
- traits
  String or string array. Match trait names such as `Button`, `StaticText`, `Toggle`, `Adjustable`.
- visible
  Boolean. Match whether the element is visible.
- hittable
  Boolean. Match whether the element can currently be hit. Action APIs usually require the target to be hittable.
- checked
  Boolean. Match confirmed state for switches, checkboxes, radio buttons, and similar controls.
- selected
  Boolean. Match whether the element is selected.
- index
  Integer. When multiple elements match, choose the Nth one. Index starts from `1`.

## Description

> Avoid using coordinates, sizes, or window identifiers as primary selectors because they are easy to change.
> If multiple elements match and no `index` is specified, action APIs may return `nil, "ambiguous target"`.
> Different apps and iOS versions may expose different fields. Keep fallback logic for important missing fields.

---

Source: [Add One or More Contacts (utils.add_contacts)](https://xxtouch.app/en/docs/handbook/utils/utils.add_contacts.md)
Path: handbook/utils/utils.add_contacts.md

# Add One or More Contacts (utils.add_contacts)

## Declaration

```lua
ok = utils.add_contacts({
    {
        firstName = "FamilyName1",
        lastName = "GivenName1",
        phoneNumbers = { "Number1-1", "Number1-2" },
        emails = { "Email1-1", "Email1-2" },
    },
    {
        firstName = "FamilyName2",
        lastName = "GivenName2",
        phoneNumbers = { "Number2-1", "Number2-2" },
        emails = { "Email2-1", "Email2-2" },
    },
    ...
})
```

## Parameters

- firstName
  String. Family name.
- lastName
  String. Given name.
- phoneNumbers
  Table. Phone numbers list.
- emails
  Table. Emails list.

## Returns

- ok
  Boolean. true on success, false on failure.

## Description

> Add one or multiple contacts to the system address book.
> Note: bulk import may take a long time.

## Examples

```lua
utils.add_contacts({
    {
        firstName = "Xiao",
        lastName = "Ming",
        phoneNumbers = { "13800001111", "13800002222" },
        emails = { "xiaoming@qq.com", "xiaoming@163.com" },
    },
    {
        firstName = "Xiao",
        lastName = "Hong",
        phoneNumbers = { "13800003333", "13800004444" },
        emails = { "xiaohong@qq.com", "xiaohong@163.com" },
    },
})
```

---

Source: [Create a VPN profile (vpnconf.create)](https://xxtouch.app/en/docs/handbook/vpnconf/vpnconf.create.md)
Path: handbook/vpnconf/vpnconf.create.md

# Create a VPN profile (vpnconf.create)

## Declaration

```lua
ok = vpnconf.create(conf)
```

## Parameters

- conf
  Table. Dictionary describing the VPN profile to create.

## Returns

- ok
  Boolean. true on success; false on failure (usually due to missing or invalid parameters).

## Description

> Quickly create a VPN profile. IKEv2 creation is not supported.

## Supported fields of conf

| Field             | Type               | Meaning                                |
|-------------------|--------------------|----------------------------------------|
| dispName          | string             | Display name of the VPN                |
| VPNType           | string             | VPN type. Supports "PPTP", "L2TP", "IPSec" |
| server            | string             | Server address                          |
| authorization     | string             | Account (username)                      |
| password          | string             | Password                                |
| secret            | string, optional   | Shared secret; can be empty for PPTP    |
| encrypLevel       | integer, optional  | Encryption level; default 1             |
| group             | string, optional   | Group name; default ""                  |
| VPNSendAllTraffic | integer, optional  | Send all traffic; default 1             |

## Example

```lua
local success = vpnconf.create{
    dispName = 'DemoVPN',              -- VPN display name
    VPNType = "L2TP",                  -- VPN type, supports PPTP, L2TP, IPSec (IKEv2 is not supported)
    server = 'vpn.example.com',        -- Server address
    authorization = 'your_account',    -- Account
    password = 'your_password',        -- Password
    secret = 'your_shared_secret',     -- Shared secret; PPTP can omit
    encrypLevel = 1,                   -- Encryption level (optional; default 1)
    group = '',                        -- Group name (optional; default "")
    VPNSendAllTraffic = 1,             -- Send all traffic (optional; default 1)
}
if success then
    sys.alert('Created successfully')
else
    sys.alert('Creation failed. Please verify the configuration is complete and correct.')
end
```
**Note**: Uses [`sys.alert`](/en/docs/handbook/sys/sys.alert.md)

---

Source: [Show a webview (webview.show)](https://xxtouch.app/en/docs/handbook/webview/webview.show.md)
Path: handbook/webview/webview.show.md

# Show a webview (webview.show)

## Declaration

```lua
webview.show { -- all fields optional
    html = HTMLContent,
    x = X,
    y = Y,
    width = Width,
    height = Height,
    corner_radius = CornerRadius,
    alpha = Opacity,
    animation_duration = Duration,
    rotate = Rotation,
    level = WindowLevel,
    opaque = Opaque,
    ignores_hit = IgnoresHit,
    can_drag = CanDrag,
    is_secure = IsSecure,
    id = Id,
}
```

## Fields

- html
  String. Optional. HTML content of the page. Defaults to the value set in the previous webview.show call.
- id
  Integer. Optional. The id of current webview (1 ~ 1000). Defaults to 1. Multiple webviews can coexist with different ids.
- x
  Integer. Optional. Distance from the left. Default 0.
- y
  Integer. Optional. Distance from the top. Default 0.
- width
  Integer. Optional. Window width. Defaults to screen width.
- height
  Integer. Optional. Window height. Defaults to screen height.
- alpha
  Number. Optional. Opacity in range 0.0 ~ 1.0. Default 1.0.
- corner_radius
  Number. Optional. Corner radius. 0.0 means squared corners. Default 0.0.
- animation_duration
  Number. Optional. Animation duration from previous state to the new state. Default 0.0.
- rotate
  Number. Optional. Rotation: 0.0 (portrait), 90.0 (landscape home-right), 180.0 (portrait upside-down), 270.0 (landscape home-left). Default 0.0.
- level
  Number. Optional. Window level. Default 1100.0.
- opaque
  Boolean. Optional. Whether the background is opaque. Default true.
- ignores_hit
  Boolean. Optional. Whether to ignore (not intercept) touch events. Default false. This cannot be changed after the webview is created.
- can_drag
  Boolean. Optional. Whether the webview can be dragged. Default false.
- is_secure (Available since XXT 1.3.8)
  Boolean. Optional. On iOS 13.2+, whether the webview is a secure view. Default false. When true, the webview cannot be captured via screenshot, color pickers, or screen recording.

## Description

- Show a webview according to the given parameters.
- Except for the html field, all other fields reset to their default values when calling show.

## Example

See [the consolidated examples at the end of this chapter](/en/docs/handbook/webview/samples.md)

---

Source: [Get current script bundle metadata (xpp.info)](https://xxtouch.app/en/docs/handbook/xpp/xpp.info.md)
Path: handbook/xpp/xpp.info.md

# Get current script bundle metadata (xpp.info)

## Declaration

```lua
info = xpp.info()
```

## Returns

- info
  Table. Returns metadata of the current XPP script bundle. If the running script is not an XPP bundle, returns an empty table.

## Description

Used to obtain metadata of the running script bundle at runtime.
See XPP spec: [XPP](/en/docs/XPP/index.md)

## Example

```lua
local info = xpp.info()
```

---

Source: [Get app data path (app.data_path)](https://xxtouch.app/en/docs/handbook/app/app.data_path.md)
Path: handbook/app/app.data_path.md

# Get app data path (app.data_path)

## Declaration

```lua
path = app.data_path(bid)
```

## Parameters

- bid
  String. App bundle identifier. You can find it in `XXT App -> More -> App List`.

## Returns

- path
  String | nil. The app's data (Documents) path, or nil if the app does not exist.

## Description

- Get the app's data path.

## Example

```lua
path = app.data_path("com.tencent.mqq") -- get QQ data path
```

---

Source: [Clear all apps' keychain items (clear.all_keychain)](https://xxtouch.app/en/docs/handbook/clear/clear.all_keychain.md)
Path: handbook/clear/clear.all_keychain.md

# Clear all apps' keychain items (clear.all_keychain)

## Declaration

```lua
clear.all_keychain()
```

## Description

> Clear keychain items for all apps.
> **WARNING:** The effect of this function is irreversible.

## Example

```lua
clear.all_keychain()
```

---

Source: [Restart script (os.restart)](https://xxtouch.app/en/docs/handbook/control-flow/os.restart.md)
Path: handbook/control-flow/os.restart.md

# Restart script (os.restart)

## Declaration

```lua
ok, err = os.restart([ scriptPath ])
```

## Parameters

- scriptPath
  String, optional. If a valid script file path is provided, the runtime restarts into that target script. Default: "" (current script).

## Returns

- ok
  Boolean. Returns false only when a target path is provided and the operation fails. On success, this function does not return because the process restarts.
- err
  String. Error message when the operation fails.

## Description

> Without the parameter, the function immediately restarts the current script process; the current script ends right away.
> With a valid script path, the current script ends and the target script starts.
> On failure (usually due to invalid arguments), the function returns false with an error message.

## Cautions

> "Current script" means the script instance that was launched, not the current file on disk. If the file changes after launch, `os.restart()` will NOT run the modified file.
> Avoid using this function in multi-threaded contexts if possible.
> Zero-delay restarts may cause other logical issues; handle accordingly.

## Example 1

```lua
os.restart() -- restart into the "current script" (not the "current script file")
```

## Example 2

```lua
os.restart(utils.launch_args().path) -- restart into the current script file
```
**Note**: Uses [`utils.launch_args`](/en/docs/handbook/utils/utils.launch_args.md)

---

Source: [Create a CoreML Vision request (coreml.new_vision_request)](https://xxtouch.app/en/docs/handbook/coreml/coreml.new_vision_request.md)
Path: handbook/coreml/coreml.new_vision_request.md

# Create a CoreML Vision request (coreml.new_vision_request)

`coreml.new_vision_request` loads a compiled CoreML model and creates a Vision-based inference request for image recognition.
Use it when the model consumes an image directly and you want Vision to handle the request pipeline.

## Declaration

```lua
vnreq, err = coreml.new_vision_request(compiled_model_path)
```

or

```lua
vnreq, err = coreml.new_vision_request({
    compiled_model_path = compiled_model_path,
    uses_cpu_only = use_cpu_only,
    compute_units = compute_units,
    image_crop_and_scale_option = crop_and_scale_mode,
})
```

## Parameters

- compiled_model_path
  String. Path to a compiled `.mlmodelc` model directory. This API is primarily designed for image classification and object detection models.

- uses_cpu_only
  Boolean, optional. Whether to use CPU only by default. Defaults to `false`.

- compute_units
  String, optional. Effective on **iOS 12+**. Supported values:
  - `"all"`
  - `"cpu_only"` or `"cpu"`
  - `"cpu_and_gpu"` or `"gpu"`
  - `"cpu_and_neural_engine"`, `"ane"`, or `"neural_engine"` (**iOS 16+**)

- image_crop_and_scale_option
  Integer, optional. Vision crop-and-scale mode used when preparing the input image.

## Returns

- vnreq
  Vision request object, or `nil` on failure.
- err
  String. `nil` on success; error message on failure.

## Notes

- Available since app version 1.3.8+.
- Not supported on iOS versions below 12.
- This function creates a Vision inference request from a compiled `.mlmodelc` model for image-based recognition.
- Use this API for Vision-based image models.
- If the model expects general `image` / `MLMultiArray` feature inputs instead of a Vision pipeline, consider [coreml.new_model_request](coreml.new_model_request.md) instead.
- In addition to `:predict()` / `:run()`, the object also exposes methods such as `:results()`, `:is_done()`, `:compute_units()`, `:image_crop_and_scale_option()`, and `:class_labels()`

## Example

See [Run image inference with a CoreML Vision request](coreml_vision_request_objectm_predict.md)

---

Source: [Get printed buffer content (print.out)](https://xxtouch.app/en/docs/handbook/develop-helper/print.out.md)
Path: handbook/develop-helper/print.out.md

# Get printed buffer content (print.out)

## Declaration

```lua
buf = print.out()
```

## Returns

- buf
  String. Empties the print buffer and returns its contents.

## Description

> Empties the print buffer and returns its contents.

## Example

```lua
-- Show the print buffer in an alert
sys.alert(print.out())
```
**Note**: Uses [`sys.alert`](/en/docs/handbook/sys/sys.alert.md)

---

Source: [Lock screen (device.lock_screen)](https://xxtouch.app/en/docs/handbook/device/device.lock_screen.md)
Path: handbook/device/device.lock_screen.md

# Lock screen (device.lock_screen)

## Declaration

```lua
device.lock_screen()
```

## Example

```lua
device.lock_screen()
```

---

Source: [Set config filename (:set_config)](https://xxtouch.app/en/docs/handbook/dialog/dialogm_set_config.md)
Path: handbook/dialog/dialogm_set_config.md

# Set config filename (:set_config)

## Declaration

```lua
dialog_obj = dialog_obj:set_config(name)
```

## Parameters

- name
  String. The name to save dialog options with

## Returns

- dialog_obj
  Dialog. Returns the dialog itself

## Description

> After the dialog is shown and the user taps Submit, the options will be saved. Next time they will be pre-selected
> Saved as a file at /private/var/mobile/Media/1ferver/uicfg/`<name>`.xcfg

## Example

```lua
dialog():set_config('cfg_name'):show()
```

## Full example

See [:show()](/en/docs/handbook/dialog/dialogm_show.md)

---

Source: [Deep serialize a table (table.deep_dump)](https://xxtouch.app/en/docs/handbook/ext-table/table.deep_dump.md)
Path: handbook/ext-table/table.deep_dump.md

# Deep serialize a table (table.deep_dump)

## Declaration

```lua
text = table.deep_dump(tab)
```

## Parameters

- tab
  Table. The table to serialize into text.

## Returns

- text
  String. A textual representation of the table's tree structure. Format compatibility is NOT guaranteed.

## Description

> Serialize a table's tree structure into text.
> The output format is NOT guaranteed to be stable across versions.
> Non-table reference types (userdata, functions) cannot be deserialized by [table.load_string](/en/docs/handbook/ext-table/table.load_string.md); human readability only.

## Example

```lua
local s = table.deep_dump(_G)
sys.alert(s)
```
**Note**: Uses [`sys.alert`](/en/docs/handbook/sys/sys.alert.md)

---

Source: [List files in a directory (file.list)](https://xxtouch.app/en/docs/handbook/file/file.list.md)
Path: handbook/file/file.list.md

# List files in a directory (file.list)

## Declaration

```lua
list, err = file.list(path [, deep])
```

## Parameters

- path
  String. Absolute directory path.
- deep (since 2025-03-13)
  Boolean, optional. Whether to recursively return full paths of files in subdirectories. Default false.

## Returns

- list
  Array or nil. nil if path does not exist or path is a file; otherwise an array of file names in the directory.
- err
  String. Error message when operation fails.

## Description

> List all file names in a directory.

## Example

```lua
local list, err = file.list("/var/mobile/")
if list then
    print("There are "..#list.." files or directories in /var/mobile/")
    for _, name in ipairs(list) do
        print(name)
    end
    sys.alert(print.out())
else
    sys.alert("/var/mobile/ is not a directory: "..err)
end
```
**Note**: Uses [`sys.alert`](/en/docs/handbook/sys/sys.alert.md)

Deep recursive example
```lua
-- full_paths = file.list(path, deep)
-- When deep is true, returns full paths recursively
list = file.list("/var/mobile/Media/1ferver", true)
nLog(list)
--[[
Possible output
{ -- table: 0xc4cc58a30
    [1] = "/var/mobile/Media/1ferver/snippets/syntax - do __ end.snippet",
    [2] = "/var/mobile/Media/1ferver/snippets/app - app.uninstall(bid).snippet",
    [3] = "/var/mobile/Media/1ferver/snippets/test - snippet.snippet",
    ...
}
--]]
```
**Note**: Uses [`nLog`](/en/docs/handbook/develop-helper/nLog.md)

---

Source: [FTP upload (ftp.upload)](https://xxtouch.app/en/docs/handbook/ftp/ftp.upload.md)
Path: handbook/ftp/ftp.upload.md

# FTP upload (ftp.upload)

## Declaration

```lua
done, info = ftp.upload(localPath, URL [, connectTimeoutSec, resumeMode, onChunk, bufferSize ])
```

## Parameters

- localPath
  String. Local file path to upload.
- URL
  String. Remote destination URL. Username and password are included in this parameter.
- connectTimeoutSec
  Number, optional. Connection timeout in seconds. Default: 10.
- resumeMode
  Boolean, optional. Enable resume (breakpoint continuation) if true. Default: false.
- onChunk
  Function, optional. Callback invoked after each chunk is transferred. Default: empty function.
  The first argument is the current transfer info. If the callback returns true, the upload is aborted.
- bufferSize
  Integer, optional. Buffer size in bytes. Default: auto-optimized.

## Returns

- done
  Boolean. Whether the connection/upload succeeded.
- info
  Table or String. If connection succeeded, returns a table with upload info; otherwise a string describing the connection failure.

## Description

```lua
-- The structure of the second return value (info) is as follows
{
    resource_size = total bytes of the local file,
    start_pos = start position in the local file for this upload,
    size_upload = bytes uploaded in this run,
    speed_upload = average speed in bytes/second,
}
```
> Suitable for large file uploads; stopping the script during transfer may be slow.
> **This function may yield; other [threads](/en/docs/handbook/thread/index.md) may run before it returns.**

## Simple example

> Put credentials in the URL. Format (brackets denote optional parts):
```lua
ftp://[user:pass@]host[:port]/path
```
> If username or password contains `@`, `:`, or `/`, use `%40`, `%3A`, `%2F` respectively. For other invalid URL characters, use URL-encode.
> Example: user `havonz`, password `11@@22`
```lua
local done, info = ftp.upload("/var/mobile/1.zip", "ftp://havonz:11%40%4022@192.168.31.13/1.zip")
if (done) then
    sys.alert("If nothing unexpected happened, the file has been uploaded.")
else
    sys.alert("Connection failed: "..info)
end
```

## Advanced example

```lua
local done, info = ftp.upload("/var/mobile/1.zip", "ftp://havonz:123456@192.168.31.13/1.zip", 10, true, function(binfo)
    local percent = math.floor(((binfo.start_pos + binfo.size_upload) / binfo.resource_size) * 100)
    sys.toast("Progress "..percent.."%")
end, 4096 * 1024)
--
if (done) then
    if (info.start_pos + info.size_upload < info.resource_size) then
        sys.alert(
            "Upload interrupted\nThis run "..info.size_upload.." bytes"
            .."\nStarted at "..info.start_pos.." byte"
            .."\nAverage speed "..math.floor(info.speed_upload/1024).." kB/s"
            .."\nRemaining "..(info.resource_size - (info.start_pos + info.size_upload)).." bytes"
        )
    else
        sys.alert(
            "Upload completed\nThis run "..info.size_upload.." bytes"
            .."\nStarted at "..info.start_pos.." byte"
            .."\nAverage speed "..math.floor(info.speed_upload/1024).." kB/s"
        )
    end
else
    sys.alert("Connection failed: "..info)
end
```
**Note**: Uses [`sys.alert`](/en/docs/handbook/sys/sys.alert.md), [`sys.toast`](/en/docs/handbook/sys/sys.toast.md)

---

Source: [Hold down a gamepad button (:down)](https://xxtouch.app/en/docs/handbook/gamepad/gamepadm_down.md)
Path: handbook/gamepad/gamepadm_down.md

# Hold down a gamepad button (:down)

> **This method is available in versions after 20260805**

## Declaration

```lua
success, err = pad:down(button)
```

## Parameters

- button
  Integer or string. An integer from `1` through `32`, one of the names below, or `"start"` or `"menu"`; string matching is case-insensitive

| Number | Button name | Aliases |
|---:|---|---|
| 1 | `a` | - |
| 2 | `b` | - |
| 3 | `x` | - |
| 4 | `y` | - |
| 5 | `left_shoulder` | `left_bumper`, `lb`, `l1` |
| 6 | `right_shoulder` | `right_bumper`, `rb`, `r1` |
| 7 | `left_trigger` | `lt`, `l2` |
| 8 | `right_trigger` | `rt`, `r2` |
| 9 | `left_stick` | `l3` |
| 10 | `right_stick` | `r3` |
| 11 | `l4` | `left_paddle` |
| 12 | `r4` | `right_paddle` |
| 13 | `m1` | - |
| 14 | `m2` | - |
| 15 | `m3` | - |
| 16 | `m4` | - |

## Returns

- success
  Boolean. True if the operation succeeds; false if the device is disconnected or busy, or if input delivery fails
- err
  String. Error message when the operation fails

## Description

- Numeric values `1` through `32` identify numeric buttons rather than button codes standardized across devices. Prefer the names in the table when possible
- Numeric buttons `17` through `32` have no predefined names and only have an effect when the target app supports the corresponding extended buttons
- `"start"` and `"menu"` are aliases for the same menu input and do not correspond to a numeric button from `1` through `32`
- The names `select`, `back`, `options`, `home`, `share`, and touchpad buttons are not currently supported
- `left_trigger` and `right_trigger` support only pressed or released states, not analog pressure. `menu` does not trigger the system Home action
- Invalid argument types, unknown names, and out-of-range values raise Lua argument errors instead of returning `false, error`

## Example

```lua
local pad = assert(gamepad.connect())

assert(pad:down("left_shoulder"))
assert(pad:up("left_shoulder"))
assert(pad:down(13))  -- numeric button 13
assert(pad:up(13))
assert(pad:disconnect())
```

---

Source: [Send GET request (http.get)](https://xxtouch.app/en/docs/handbook/http/http.get.md)
Path: handbook/http/http.get.md

# Send GET request (http.get)

## Declaration

```lua
status, headersJson, body = http.get(URL [, timeoutSec, headers, URLNoEscape ])
```

## Declaration (named arguments)

**Supported since 2025-06-25; progress options are supported since 2026-04-02**
```lua
status, headersJson, body = http.get{
    url = URL;
    timeout = timeoutSec;
    headers = headers;
    params = queryParams;
    download_file = savePathIfSuccess;
    progress = progressCallback;
    progress_interval_ms = progressIntervalMs;
}
```

## Parameters

- URL
  String. Target URL. By default the URL will be percent-escaped; see **URLNoEscape** if you want to disable escaping.
- timeoutSec
  Number, optional. Timeout in seconds. Default: 10.
- headers
  Table, optional. Request headers as `{field1 = value1, ...}`. Default: `{}`.
- queryParams
  Table, optional. Query parameters as `{field1 = value1, ...}`. Default: `{}`.
- savePathIfSuccess
  String, optional. If set, the response body will be saved to this file and the body return value will be that path.
- progressCallback
  Function, optional. Supported since 2026-04-02. Called when request progress changes. The first argument is the current progress info.
- progressIntervalMs
  Integer, optional. Supported since 2026-04-02. Progress callback interval in milliseconds.
- URLNoEscape
  Boolean, optional. true = do not escape URL. Default: false.
  For custom escaping, see [lcurl module](/en/docs/handbook/open-source/lcurl.md) `easy:escape` and `easy:unescape`.

## Returns

- status
  Integer. HTTP status code; -1 if timed out.
- headersJson
  String or nil. Response headers in JSON format; nil on timeout.
- body
  String or nil. Response body; or file path if saved to file; nil on timeout.

## Description

> Performs an HTTP/1.1 GET request.
> This function does not store resources to disk. For large downloads, use [`http.download`](/en/docs/handbook/http/http.download.md).
> **This function may yield; other [threads](/en/docs/handbook/thread/index.md) may run before it returns.**
> If the server only supports HTTP/1.0 or 0.9, you can use `httpGet` instead:
```lua
body = httpGet(URL, timeoutSec)
```

The `info` table passed to the progress callback has this structure:

```lua
{
    count_of_bytes_sent = bytesSent;
    count_of_bytes_expected_to_send = bytesExpectedToSend;
    count_of_bytes_received = bytesReceived;
    count_of_bytes_expected_to_receive = bytesExpectedToReceive;
}
```

## Example

```lua
local code, res_headers, body = http.get("https://httpbin.org/get?hello=world&你好=世界", 15, {
    ["User-Agent"] = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0)"; -- mimic IE8
    ["Cookie"] = "a=1; b=2; c=3"; -- send cookies
})
if code == 200 then
    sys.alert(body)
end
```
**Note**: Uses [`sys.alert`](/en/docs/handbook/sys/sys.alert.md)

## Example (named arguments)

```lua
local code, res_headers, body = http.get{
    url = "https://httpbin.org/get";
    timeout = 15;
    headers = {
        ["User-Agent"] = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0)";
        ["Cookie"] = "a=1; b=2; c=3";
    };
    params = {
        ["hello"] = "world";
        ["你好"] = "世界";
    };
}
if code == 200 then
    sys.alert(body)
end
```
**Note**: Uses [`sys.alert`](/en/docs/handbook/sys/sys.alert.md)

## Example: get public IP

```lua
function get_ip()
    local done = false
    thread.dispatch(function()
        while (true) do
            if (done) then
                sys.toast("", -1)
                return
            else
                sys.toast("Fetching IP...", device.front_orien())
            end
            sys.msleep(2000)
        end
    end)
    while (true) do
        local c, h, b = http.get("https://ip.chinaz.com/?ts="..tostring(sys.rnd()), 60)
        if (c==200) then
            sys.toast("", -1)
            done = true
            return b:match('%d%d?%d?%.%d%d?%d?%.%d%d?%d?%.%d%d?%d?')
        end
    end
end
--
sys.alert(get_ip())
```
**Note**: Uses [`sys.alert`](/en/docs/handbook/sys/sys.alert.md), [`sys.toast`](/en/docs/handbook/sys/sys.toast.md), [`sys.msleep`](/en/docs/handbook/sys/sys.msleep.md), [`sys.rnd`](/en/docs/handbook/sys/sys.rnd.md), [`thread.dispatch`](/en/docs/handbook/thread/thread.dispatch.md), [`device.front_orien`](/en/docs/handbook/device/device.front_orien.md)

---

Source: [Create a blank image with specified size (image.new)](https://xxtouch.app/en/docs/handbook/image/image.new.md)
Path: handbook/image/image.new.md

# Create a blank image with specified size (image.new)

## Declaration

```lua
img = image.new(width, height)
```

## Parameters

- width, height
  Integer. Width and height of the new image

## Returns

- img
  Image object. The newly created image

## Description

> Create a blank image. All pixels are initialized to 0x000000 (black)
> This call creates a new image object. For efficient frequent usage, please pair with [image:destroy](/en/docs/handbook/image/imagem_destroy.md)

---

Source: [Encode a Lua value to JSON string (json.encode)](https://xxtouch.app/en/docs/handbook/json/json.encode.md)
Path: handbook/json/json.encode.md

# Encode a Lua value to JSON string (json.encode)

## Declaration

```lua
jsonText, err = json.encode(value)
```

## Parameters

- value
  Table or String or Number or Boolean or json.null. The Lua value to convert to JSON text.

## Returns

- jsonText
  String or nil. JSON string on success; nil on failure.
- err
  String or nil. Error message when conversion fails (i.e., when jsonText is nil).

## Description

> Converting Lua values to JSON makes it easy to interoperate with other languages.
> Note: not every Lua value can be encoded to JSON, e.g., userdata, functions, or tables containing them.
> This function can be used in XUI.

## Example

```lua
local tb = {
    ["name"] = "alice",
    ["message"] = "hello, world",
    scores = {
        90, 85, 72, 100, 68,
    },
    nullvalue = json.null,
}
local jsonstr = json.encode(tb)
sys.alert(jsonstr)
--
local tmp = json.decode(jsonstr)
sys.alert(tmp.scores[4])
sys.alert(tostring(tmp.nullvalue))
```
**Note**: Uses [`sys.alert`](/en/docs/handbook/sys/sys.alert.md)

---

Source: [Hold down a physical key (key.down)](https://xxtouch.app/en/docs/handbook/key/key.down.md)
Path: handbook/key/key.down.md

# Hold down a physical key (key.down)

> **The hardware keyboard behavior described on this page is available in versions after 20260805**

## Declaration

```lua
key.down(keycode)
```

## Parameters

- keycode
  String. Physical key code. See [Samples and supported key codes](/en/docs/handbook/key/samples.md).

## Description

> Simulate pressing down a physical key.
> **Important:** Without a global hardware keyboard, call the corresponding [`key.up`](/en/docs/handbook/key/key.up.md) afterwards. Otherwise the key may remain held even after the script ends. A global hardware keyboard releases all held keys when it is disconnected or the script stops.

- After a [global hardware keyboard](key.connect_global_keyboard.md) is connected, standard keyboard and keypad keys use that object. Media and vendor-defined keys keep their previous behavior
- This function remains paired with the matching `key.up`. If the hardware keyboard has already disconnected, the key was released during disconnection and the later `key.up` sends no input
- Calls through `key(...):down()` follow the same rules

## Example

See [the consolidated examples at the end of this chapter](/en/docs/handbook/key/samples.md).

---

Source: [Move the hardware mouse (:move)](https://xxtouch.app/en/docs/handbook/mouse/mousem_move.md)
Path: handbook/mouse/mousem_move.md

# Move the hardware mouse (:move)

> **This method is available in versions after 20260805**


## Declaration

```lua
success, error_message = mouse_obj:move(dx, dy)
```


## Parameters

- dx
  Integer. Relative horizontal movement in the range `[-2047, 2047]`; positive values move right and negative values move left.
- dy
  Integer. Relative vertical movement in the range `[-2047, 2047]`; positive values move down and negative values move up.


## Returns

- success
  Boolean. `true` if the movement succeeds; otherwise `false`.
- error_message
  String. The reason the movement failed.


## Description

> Move once relative to the current pointer position.
> The interface does not automatically split movement beyond the supported range. Out-of-range values raise a Lua argument error.


## Example

```lua
local m = assert(mouse.connect())
assert(m:move(100, -50))
assert(m:disconnect())
```

---

Source: [ONNX Runtime Session Module](https://xxtouch.app/en/docs/handbook/onnxruntime/onnxruntime.session_module.md)
Path: handbook/onnxruntime/onnxruntime.session_module.md

# ONNX Runtime Session Module

> **This module is available in versions released after 20260402**

Session objects handle model loading, input/output inspection, and inference execution.

## Runtime configuration

### `onnxruntime.configure(opts)`

```lua
assert(onnxruntime.configure({
    log_severity_level = 2,
    log_id = "my-runtime",
    use_global_thread_pools = false,
    global_intra_op_num_threads = 0,
    global_inter_op_num_threads = 0,
}))
```

Notes:

- It must be called before creating any session
- Calling it again after an active session already exists returns an error

Supported fields:

- `log_severity_level`
- `log_id`
- `use_global_thread_pools`
- `global_intra_op_num_threads`
- `global_inter_op_num_threads`

## Create a session

### `onnxruntime.session(model_path[, opts])`

```lua
session, err = onnxruntime.session(model_path, opts)
```

Loads an ONNX model from a file path.

### `onnxruntime.session_from_bytes(model_bytes[, opts])`

```lua
session, err = onnxruntime.session_from_bytes(model_bytes, opts)
```

Creates a session from in-memory model bytes.

## Session options

### General fields

- `providers` or `provider`
  Accepts a string or array of strings; the currently handled provider strings are `"cpu"` and `"coreml"`, and aliases such as `CPUExecutionProvider` and `CoreMLExecutionProvider` are also accepted
- `fallback_to_cpu`
  Boolean, default `true`
- `intra_op_num_threads`
- `inter_op_num_threads`
- `log_id`
- `session_log_severity_level`
- `session_log_verbosity_level`
- `optimized_model_path`
- `profile_file_prefix`
- `free_dimension_overrides`
- `config_entries`
- `graph_optimization_level`
  One of `"disable"`, `"basic"`, `"extended"`, or `"all"`
- `execution_mode`
  One of `"sequential"` or `"parallel"`
- `deterministic_compute`
- `disable_per_session_threads`
- `enable_cpu_mem_arena`
- `enable_mem_pattern`
- `custom_op_libraries`

Additional notes:

- `free_dimension_overrides` must be an array table, and each item must look like `{ by = "name"|"denotation", key = "...", value = integer }`
- `config_entries` must be a string-to-string table
- `custom_op_libraries` may be a single path string, an array of paths, or handles returned by `load_custom_op_library()`; arrays may mix paths and handles
- If `providers` is omitted, or the provider list is empty, the current implementation adds the CPU provider by default
- When `"coreml"` is present and `fallback_to_cpu = true`, session creation can fall back to CPU if CoreML provider initialization fails
- If you explicitly pass `providers = {"coreml", "cpu"}`, that order means CoreML first, CPU second

### CoreML provider fields

When `"coreml"` is included in `providers`, these fields are also supported:

- `coreml_compute_units`
  Prefer `"all"`, `"cpu_only"`, `"cpu_and_gpu"`, or `"cpu_and_neural_engine"`; the parser also accepts aliases such as `CPUOnly`, `CPUAndGPU`, `CPUAndNeuralEngine`, and `MLComputeUnits...`
- `coreml_create_mlprogram`
- `coreml_require_static_input_shapes`
- `coreml_enable_on_subgraph`
- `coreml_flags`
- `coreml_use_cpu_only`
- `coreml_use_cpu_and_gpu`
- `coreml_only_enable_device_with_ane`

Additional notes:

- `coreml_flags`, `coreml_use_cpu_only`, `coreml_use_cpu_and_gpu`, and `coreml_only_enable_device_with_ane` are legacy compatibility fields
- New and legacy fields can be mixed, but session creation fails immediately if they express conflicting meanings
- `coreml_only_enable_device_with_ane` cannot be combined with mutually exclusive settings such as `coreml_compute_units = "cpu_only"` or `"cpu_and_gpu"`

## Session object methods

### Basic inspection

- `session:input_names()`
- `session:output_names()`
- `session:overridable_initializer_names()`
- `session:input_count()`
- `session:output_count()`
- `session:overridable_initializer_count()`

### Type information

- `session:input_info(name_or_index)`
- `session:output_info(name_or_index)`
- `session:overridable_initializer_info(name_or_index)`

The returned table may contain:

- `name`
- `onnx_type`
- `is_sparse`
- `data_type`
- `type`
- `has_shape`
- `shape`
- `symbolic_shape`
- `element`
- `key_type`
- `value`

Notes:

- tensor / sparse tensor entries include `data_type`, `shape`, and `symbolic_shape`
- sequence / optional entries include nested `element`
- map entries include `key_type` and nested `value`

### Memory information

- `session:memory_info_for_inputs()`
- `session:memory_info_for_outputs()`

The result supports both numeric-order and name-based access. Individual entries commonly contain:

- `name`
- `id`
- `mem_type`
- `allocator_type`
- `device_type`
- `device_mem_type`
- `vendor_id`

### Metadata and lifecycle

- `session:metadata()`
- `session:close()`
- `session:end_profiling()`
- `session:profiling_start_time_ns()`
- `session:set_ep_dynamic_options(opts)`
- `session:register_custom_op_library(path_or_handle)`

Notes:

- `end_profiling()` returns the profiling output file path
- `set_ep_dynamic_options()` stringifies all keys and values before passing them to ORT
- `register_custom_op_library()` rebuilds the underlying session using the current session options plus the new library
- `path_or_handle` may be either a file path or a handle returned by `load_custom_op_library()`

## Run inference

### `session:run(inputs[, output_names[, run_options]])`

```lua
outputs, err = session:run({
    input_ids = input_tensor,
    attention_mask = mask_tensor,
}, {
    "logits",
}, run_options)
```

### `session:run_into(inputs, outputs[, run_options])`

```lua
outputs, err = session:run_into({
    x = input_tensor,
}, {
    y = reused_output_tensor,
}, run_options)
```

### `session:run_with_iobinding(binding[, run_options])`

```lua
outputs, err = session:run_with_iobinding(binding, run_options)
```

Input rules:

- `inputs` can be a positional array or a dictionary keyed by input name
- Positional arrays follow model input order and can continue with overridable initializers
- Dictionary keys must match input names or overridable initializer names
- Optional inputs can be omitted, or passed as `onnxruntime.optional(nil, type_info)`

Output rules:

- The return value is a table
- Each output can be accessed both by numeric index and by output name
- If `run_into()` reuses an existing output tensor, the returned table contains the same object

## Run options

### `onnxruntime.run_options([opts])`

```lua
local run_options = assert(onnxruntime.run_options({
    tag = "session-run",
    log_severity_level = 2,
    log_verbosity_level = 1,
}))
```

Supported fields:

- `tag`
- `log_severity_level`
- `log_verbosity_level`

Object methods:

- `run_options:tag([value])`
- `run_options:log_severity_level([value])`
- `run_options:log_verbosity_level([value])`
- `run_options:terminate()`
- `run_options:reset_terminate()`

## IOBinding

### `session:create_io_binding()`

```lua
binding, err = session:create_io_binding()
```

### `binding:bind_input(name, value)`

Binds an input value. Empty optionals are not accepted here.

### `binding:bind_output(name[, spec_or_tensor])`

Supports three forms:

- `binding:bind_output("y")`
  Binds to CPU memory and retrieves it later with `get_outputs()`
- `binding:bind_output("y", existing_tensor)`
  Writes directly into an existing tensor
- `binding:bind_output("y", {type = "float32", shape = {1, 2}})`
  Creates and returns a new output tensor through the API

It also supports:

- `binding:bind_output("y", {mode = "device"})`

### Other methods

- `binding:clear_inputs()`
- `binding:clear_outputs()`
- `binding:synchronize_inputs()`
- `binding:synchronize_outputs()`
- `binding:get_outputs()`

## Example

```lua
local ort = require("onnxruntime")

local session = assert(ort.session(XXT_HOME_PATH.."/models/demo/model.onnx", {
    providers = {"coreml", "cpu"},
    fallback_to_cpu = true,
    coreml_compute_units = "all",
}))

local x = assert(ort.tensor("float32", {1, 2}, {1.0, 2.0}))
local bias = assert(ort.tensor("float32", {1, 2}, {0.5, -0.5}))
local run_options = assert(ort.run_options({tag = "demo"}))

local outputs = assert(session:run({
    x = x,
    bias = bias,
}, {"y"}, run_options))

print(outputs.y:to_table()[1])
```

---

Source: [LuaSocket](https://xxtouch.app/en/docs/handbook/open-source/luasocket.md)
Path: handbook/open-source/luasocket.md

# LuaSocket

[LuaSocket manual](https://w3.impa.br/~diego/software/luasocket/reference.html)

---

## Example: connection timeout

```lua
local socket = require("socket")
local sock = socket.tcp()
sock:settimeout(0.2) -- set connection timeout in seconds
if (sock:connect("220.181.57.217", 80)) then
    sock:close()
    sys.alert("Connected")
else
    sys.alert("Timeout")
end
```
**Note**: Uses [`sys.alert`](/en/docs/handbook/sys/sys.alert.md)

## Example: simulate HTTP GET for Baidu homepage

```lua
local socket = require('socket')

local sock = socket.tcp()
local ip = assert(socket.dns.toip('www.baidu.com'), 'DNS resolve failed')
sock:settimeout(10)
assert(sock:connect(ip, 80) == 1, 'Connect failed or timeout')

assert(
    sock:send(
        'GET / HTTP/1.1\r\n'..
        'Host: www.baidu.com\r\n'..
        'Accept: */*\r\n'..
        'Connection: close\r\n'..
        '\r\n'
    ),
    'Send timeout'
)

local buf = {}
repeat
    local chunk, status, partial = sock:receive(4096)
    if (chunk) then
        buf[#buf + 1] = chunk
    else
        if (partial) then
            buf[#buf + 1] = partial
        end
    end
until status == "closed"
sock:close()

sys.alert(table.concat(buf))
```
**Note**: Uses [`sys.alert`](/en/docs/handbook/sys/sys.alert.md), [table.concat](https://www.lua.org/manual/5.3/manual.html#pdf-table.concat)

---

Source: [Write pasteboard items (pasteboard.write_items)](https://xxtouch.app/en/docs/handbook/pasteboard/pasteboard.write_items.md)
Path: handbook/pasteboard/pasteboard.write_items.md

# Write pasteboard items (pasteboard.write_items)

## Declaration

```lua
pasteboard.write_items(item [, options ])
pasteboard.write_items(items [, options ])
```

## Parameters

- item
  Table. A pasteboard item whose keys are UTIs and values are string data.
- items
  Table. A list of pasteboard items.
- options
  Table, optional.
  `local_only`: Boolean. Keep the content local to this device. Supported on iOS 10 and later.
  `expiration_date`: Number. Unix timestamp in seconds. Supported on iOS 10 and later.

  <details>
  <summary>Pasteboard item structure</summary>

  ```lua
  {
      ["public.utf8-plain-text"] = "plain text",
      ["public.rtf"] = "RTF data",
      ["public.html"] = "HTML data",
      ["public.png"] = "PNG binary data",
      ...
  }
  ```
  </details>

## Returns

- success
  Boolean. Returns `true` when writing succeeds; otherwise returns `false`.

## Description

> Write pasteboard items to the system pasteboard. A single item can provide multiple format representations.
> iOS 9 ignores `options`.
> **This function is available in versions after 20260428.**

## Example

```lua
pasteboard.write_items({
    {
        ["public.utf8-plain-text"] = "normal bold italic red\nHello",
        ["public.rtf"] = [[{\rtf1\ansi\deff0
{\fonttbl{\f0 Helvetica;}}
{\colortbl;\red255\green0\blue0;}
\f0\fs32 normal {\b bold} {\i italic} \cf1 red\cf0\par
Hello
}]],
        ["public.html"] = [[<p>normal <b>bold</b> <i>italic</i> <span style="color:red">red</span><br>Hello</p>]],
    },
}, {
    local_only = true,
    expiration_date = os.time() + 3600,
})
```

---

Source: [Write a plist file (plist.write)](https://xxtouch.app/en/docs/handbook/plist/plist.write.md)
Path: handbook/plist/plist.write.md

# Write a plist file (plist.write)

## Declaration

```lua
plist.write(filePath, tab)
```

## Parameters

- filePath
  String. Absolute path of the plist file to write.
- tab
  Table. The table (tree) to be converted to plist and written.

## Description

> Write a Lua table (tree) to a plist file.
> This function can be used in XUI.

## Example

```lua
local plfilename = "/var/mobile/Library/Caches/com.apple.mobile.installation.plist"
local tmp2 = plist.read(plfilename)
tmp2["Metadata"]["ProductBuildVersion"] = "CustomBuild"
plist.write(plfilename, tmp2)
sys.chown(plfilename, 501, 501)  -- fix ownership
sys.chmod(plfilename, "0644")    -- fix permission
```

---

Source: [Read a value from process dict (proc_get)](https://xxtouch.app/en/docs/handbook/proc/proc_get.md)
Path: handbook/proc/proc_get.md

# Read a value from process dict (proc_get)

## Declaration

```lua
value = proc_get(key)
```

## Parameters

- key
  String.

## Returns

- value
  String. Returns the stored value at the key; if none, returns empty string.

## Description

- All process dict entries whose keys start with "xxtouch." or "1ferver." are reserved.
- Read the value from the specified key in the process dictionary.
- Returns empty string if no value existed.

## Example

```lua
local bill = proc_get("billno")
if bill ~= "" then
    print("has a bill: ".. bill)
else
    print("no bill")
end
```

---

Source: [Get Screen Size (screen.size)](https://xxtouch.app/en/docs/handbook/screen/screen.size.md)
Path: handbook/screen/screen.size.md

# Get Screen Size (screen.size)

## Declaration

```lua
width, height = screen.size()
```

## Returns

- width: integer
- height: integer

## Description

> The return value is not affected by the current orientation of the Home screen or apps, and is not affected by Display Zoom.
> This function can be used in XUI.

## Example

```lua
-- Determine device model by resolution
width, height = screen.size()
if width == 640 and height == 1136 then
    -- iPhone 5, 5S, iPod touch 5
elseif width == 640 and height == 960 then
    -- iPhone 4, 4S, iPod touch 4
elseif width == 750 and height == 1334 then
    -- iPhone 6, 6S, 7, 8
elseif width == 1242 and height == 2208 then
    -- iPhone 6+, 6S+, 7+, 8+
elseif width == 768 and height == 1024 then
    -- iPad 1, 2, mini 1
elseif width == 1536 and height == 2048 then
    -- iPad 3, 4, 5, mini 2
elseif width == 320 and height == 480 then
    -- iPhone 3GS / iPhone 4 (listed for completeness; XXTouch does not support devices that old)
end
```

---

Source: [Extension Libraries and Remote Extension API](https://xxtouch.app/en/docs/handbook/supplement/exts.md)
Path: handbook/supplement/exts.md

# Extension Libraries and Remote Extension API

## Extension Libraries

Beyond the extension libraries compiled by the XXTouch team, developers can build their own extensions for XXTouch. Download the template below to get started:
> [Lua Plugin Template.zip](/zip/Lua插件模板.zip)

## Remote Extension API

If you are interested in building companion software for the XXTouch ecosystem — such as a LAN-based centralized control system, screenshot color picker, script development environment, or inter-device data sharing tool — see the [OpenAPI](/OpenAPI/README.md) documentation.

---

Source: [System Alert (sys.alert)](https://xxtouch.app/en/docs/handbook/sys/sys.alert.md)
Path: handbook/sys/sys.alert.md

# System Alert (sys.alert)

## Declaration

```lua
choice = sys.alert(text [, autoDismissSeconds, title, button0Title, button1Title, button2Title ])
```

## Parameters

- text
  String. The alert message body.
- autoDismissSeconds
  Number, optional. Auto-dismiss timeout in seconds. Set `0` to disable auto-dismiss. Default: `0`.
- title
  String, optional. Alert title. Default: `"Script Alert"`.
- button0Title (Cancel)
  String, optional. Title of the default button. Default: `"OK"`.
- button1Title
  String, optional. Title of the first extra button. Hidden if not provided.
- button2Title
  String, optional. Title of the second extra button. Hidden if not provided.

## Returns

- choice
  Integer.
  - `0` = button0 (Cancel)
  - `1` = button1
  - `2` = button2
  - `3` = auto-dismissed when the timeout elapses
  - `71` = SpringBoard crashed while waiting

## Description

> Pops up a system alert dialog with up to 3 buttons. Blocks all threads until a result is returned.
> **For versions after 2026-01-08, this function yields in a multitasking environment; other threads may run while waiting for user input.**

## Example

```lua
local choice = sys.alert('What are you going to do?', 10, 'Your Choice', 'Cancel', 'Eat', 'Sleep')
if choice==0 then
    sys.alert('You chose “Cancel”')
elseif choice==1 then
    sys.alert('You chose “Eat”')
elseif choice==2 then
    sys.alert('You chose “Sleep”')
elseif choice==3 then
    sys.alert('No choice, timed out')
else
    sys.alert('SpringBoard crashed')
end
```

---

Source: [Activator event callback](https://xxtouch.app/en/docs/handbook/system-callback/activator.md)
Path: handbook/system-callback/activator.md

# Activator event callback

## Declaration

```lua
thread.register_event("xxtouch.activator_callback", function(val)
    local ret = json.decode(val)
    sys.toast("mode:"..ret.mode.."\n"
            .."event:"..ret.event.."\n"
            .."time:"..ret.time)
end)
```

## State

- val
  When [Activator](https://cydia.saurik.com/package/libactivator/) is configured for callbacks and a corresponding event is triggered, the event details are passed here.

## Description

> Requires installing [Activator](https://cydia.saurik.com/package/libactivator/) and configuring it appropriately in Activator.

## Example

```lua
-- Clear message queue
proc_queue_clear("xxtouch.activator_callback")
--
-- Start listening
local eid = thread.register_event("xxtouch.activator_callback", function(val)
    local ret = json.decode(val)
    if ret.event=="libactivator.statusbar.tap.double" then
        sys.toast("Double-tap status bar callback")
    end
end)
--
sys.msleep(20000) -- wait 20 seconds
--
-- Unregister callback; without unregistering, the script will not end here
thread.unregister_event("xxtouch.activator_callback", eid)
```
**Note**: Uses [`sys.toast`](/en/docs/handbook/sys/sys.toast.md), [`sys.msleep`](/en/docs/handbook/sys/sys.msleep.md), [`proc_queue_clear`](/en/docs/handbook/proc/proc_queue_clear.md), [`thread.register_event`](/en/docs/handbook/thread/thread.register_event.md), [`thread.unregister_event`](/en/docs/handbook/thread/thread.unregister_event.md)

---

Source: [Get current task ID (thread.current_id)](https://xxtouch.app/en/docs/handbook/thread/thread.current_id.md)
Path: handbook/thread/thread.current_id.md

# Get current task ID (thread.current_id)

## Declaration

```lua
tid = thread.current_id()
```

## Returns

- tid
  Integer. The id of the current task.

## Example

See [the consolidated examples at the end of this chapter](/en/docs/handbook/thread/samples.md)

---

Source: [Touch Down (touch.on)](https://xxtouch.app/en/docs/handbook/touch/touch.on.md)
Path: handbook/touch/touch.on.md

# Touch Down (touch.on)

## Declaration

```lua
evt = touch.on(x, y)
```

## Parameters

- x, y
  Integers. Coordinates of the contact point in the current rotated coordinate system.

## Returns

- evt
  A touch event object used to control this touch process.

## Description

> Simulates touching down at the specified position and returns a touch event object to operate this touch.
> Coordinate parameters follow the coordinate system initialized via [`screen.init`](/en/docs/handbook/screen/screen.init.md).
> **Note:** A finger ID is allocated automatically from a limited pool (about 30). Exceeding the limit when calling [touch.on](/en/docs/handbook/touch/touch.on.md) or [touch.tap](/en/docs/handbook/touch/touch.tap.md) throws a `finger pool overflow` error. Do not keep too many finger IDs active at once; release them promptly with `:off`.
> You may also call with an explicit finger id (must be between 1 and 29), in which case you manage the id yourself:
```lua
touch.on(fingerId, x, y)
```

## Example

```lua
-- Touch down at (100,100), move linearly to (200,200), then lift
touch.on(100, 100):move(200, 200):off()

-- Use explicit finger id 1
touch.on(1, 100, 100)
touch.off(1)
```

---

Source: [Element Fields](https://xxtouch.app/en/docs/handbook/ui_element/element.md)
Path: handbook/ui_element/element.md

# Element Fields

> **This module is available in versions after 20260507**

Elements returned by query APIs are plain Lua tables. Fields come from the current UI, so different apps and control types may return different fields.

## Common Fields

- text
  String. Readable title of the element.
- value
  Any type. Current value of the element. Text fields usually expose current text, switches may expose `0` or `1`, and sliders may expose percentage text.
- identifier
  String. Element identifier.
- hint
  String. System hint text.
- bundleId
  String. Bundle identifier of the app that owns the element.
- x / y / width / height
  Integer. Element frame in physical pixels.
- centerPoint
  Table. Element center point in physical pixels, for example `{ x = 100, y = 200 }`.
- children
  Table. Child element array. Expansion depth is controlled by `max_level`.
- traits
  Integer. Raw trait value.
- traitsDescription
  Table. Trait name array, such as `Button`, `StaticText`, `Toggle`, `Adjustable`.
- isVisible
  Boolean. Whether the element is visible.
- isSelected
  Boolean. Whether the element is selected.
- isToggle
  Boolean. Whether the element behaves like a switch.
- isAdjustable
  Boolean. Whether the element supports increase or decrease.
- checked
  Boolean. Confirmed state for switches, checkboxes, radio buttons, and similar controls. It may be absent when the state cannot be read reliably.
- hasTextEntry
  Boolean. Whether the element looks like a text input target.
- isKeyboardKey
  Boolean. Whether the element looks like a keyboard key.
- absoluteValue
  Number. Normalized value that may appear on adjustable controls such as sliders.

## Hit State Fields

These fields may appear only when `include_hit_state`, `hit_test`, `fallback_hit_test`, or an action check is used:

- canHit
  Boolean. Whether the element can currently be hit from the top layer.
- hitVerified
  Boolean. Whether hit state has been checked.
- hitTestPoint
  Table. Hit point in physical pixels.

## Description

> Element fields are useful for reading and checking current UI state.
> For stable targeting, prefer semantic fields such as `text`, `role`, `checked`, and `selected`.
> After the UI changes, query the element again or capture a new snapshot.

---

Source: [Remove All Contacts (utils.remove_all_contacts)](https://xxtouch.app/en/docs/handbook/utils/utils.remove_all_contacts.md)
Path: handbook/utils/utils.remove_all_contacts.md

# Remove All Contacts (utils.remove_all_contacts)

## Declaration

```lua
ok = utils.remove_all_contacts()
```

## Returns

- ok
  Boolean. true on success, false on failure.

## Description

> Remove all contacts from the address book.
> May take a while if there are many contacts.

## Examples

```lua
utils.remove_all_contacts()
```

---

Source: [Get current system VPN list (vpnconf.list)](https://xxtouch.app/en/docs/handbook/vpnconf/vpnconf.list.md)
Path: handbook/vpnconf/vpnconf.list.md

# Get current system VPN list (vpnconf.list)

## Declaration

```lua
list = vpnconf.list()
```

## Returns

- list
  Table or nil. On success, returns an array of current system VPNs; nil on failure.

  <details>
  <summary>Returned VPN list structure</summary>

  ```lua
  {
      {dispName = name1, VPNID = id1},
      {dispName = name2, VPNID = id2},
      ...
  }
  ```
  </details>

## Example

```lua
local list = vpnconf.list()
if list then
    sys.alert(table.deep_dump(list))
else
    sys.alert('Failed to fetch list')
end
```
**Note**: Uses [`sys.alert`](/en/docs/handbook/sys/sys.alert.md), [`table.deep_dump`](/en/docs/handbook/ext-table/table.deep_dump.md)

---

Source: [Hide a webview (webview.hide)](https://xxtouch.app/en/docs/handbook/webview/webview.hide.md)
Path: handbook/webview/webview.hide.md

# Hide a webview (webview.hide)

## Declaration

```lua
webview.hide([ id ])
```

## Parameters

- id
  Integer. Optional. Current webview id (1 ~ 1000). Default 1.

## Description

Temporarily hide a webview.

## Example

See [the consolidated examples at the end of this chapter](/en/docs/handbook/webview/samples.md)

---

Source: [Get current script bundle path (xpp.bundle_path)](https://xxtouch.app/en/docs/handbook/xpp/xpp.bundle_path.md)
Path: handbook/xpp/xpp.bundle_path.md

# Get current script bundle path (xpp.bundle_path)

## Declaration

```lua
bundle_path = xpp.bundle_path()
```

## Returns

- bundle_path
  String. Returns the current script bundle path. If the running script is not an XPP bundle, returns the path of the running script file.

## Description

> Used to obtain the bundle path of the currently running script at runtime.
> See XPP spec: [XPP](/en/docs/XPP/index.md)

## Example

```lua
local path = xpp.bundle_path()
```

---

Source: [Get screen scale factor (screen.scale_factor)](https://xxtouch.app/en/docs/handbook/screen/screen.scale_factor.md)
Path: handbook/screen/screen.scale_factor.md

# Get screen scale factor (screen.scale_factor)


## Declaration

```lua
local factor = screen.scale_factor()
```


## Return Value

- factor
    Number indicating the ratio between device pixels and logical points (pt)


## Description

> Use the return value to convert between the physical pixel resolution and the logical coordinate system.
> Common values: 2.0 (most Retina iPhones and iPads), 3.0 (Plus/Max models and recent full-screen iPhones). Modern iPhones rarely use non-Retina 1.0 scale.
> Combine with `screen.size()` to derive logical dimensions: `width_pt = width_px / factor`. Image search and color sampling still work with pixel sizes; only when working with point-based UI coordinates do you need to convert.


## Example

```lua
-- Convert pixel resolution to logical points
local w_px, h_px = screen.size()
local scale = screen.scale_factor()
local w_pt, h_pt = w_px / scale, h_px / scale

sys.log(string.format("Pixel resolution: %dx%d, scale: %.1fx, logical points: %.0fx%.0f", w_px, h_px, scale, w_pt, h_pt))

-- Adjust UI coordinates based on the scale factor
local x_point, y_point = 100, 200           -- Coordinates in points from Apple HIG or third-party UI specs
local x_px, y_px = x_point * scale, y_point * scale

touch.tap(x_px, y_px)
```
**Note**: The sample uses functions outside this chapter: [`sys.log`](/en/docs/handbook/sys/sys.log.md), [`touch.tap`](/en/docs/handbook/touch/touch.tap.md)

---

Source: [Get app group info (app.group_info)](https://xxtouch.app/en/docs/handbook/app/app.group_info.md)
Path: handbook/app/app.group_info.md

# Get app group info (app.group_info)

## Declaration

```lua
group_info = app.group_info(bid)
```

## Parameters

- bid
  String. App bundle identifier. You can find it in `XXT App -> More -> App List`.

## Returns

- group_info
  Table. App group info as key-value pairs: `{group_id = data_path, ...}`. Returns an empty table if none exist.

## Example

```lua
local function clear_dir(path)
    for _, fn in ipairs(file.list(path) or {}) do
        local full_path = path .. '/' .. fn
        file.remove(full_path)
    end
end
--
local info = app.group_info("com.tencent.mqq") -- Get QQ's app group info
--
-- Loop through and delete all contents in app group directories
for _,p in pairs(info) do
    for _,v in ipairs(file.list(p) or {}) do
        local path = p .. '/' .. v
        if file.exists(path) == 'directory' then
            clear_dir(path)
        elseif v ~= '.com.apple.mobile_container_manager.metadata.plist' then
            file.remove(path)
        end
    end
end
```

---

Source: [Clear browser Cookies (clear.cookies)](https://xxtouch.app/en/docs/handbook/clear/clear.cookies.md)
Path: handbook/clear/clear.cookies.md

# Clear browser Cookies (clear.cookies)

## Declaration

```lua
clear.cookies()
```

## Description

> Clear browser Cookies.
> **WARNING:** The effect of this function is irreversible.

## Example

```lua
clear.cookies()
```

---

Source: [Register exit callback (register_atexit)](https://xxtouch.app/en/docs/handbook/control-flow/register_atexit.md)
Path: handbook/control-flow/register_atexit.md

# Register exit callback (register_atexit)


## Declaration

```lua
original_callback = register_atexit(name, callback)
```


## Parameters

- name
    String, required. Identifier for the registered callback; reusing the same `name` replaces the existing one.
- callback
    Function, required. The function to run when the script exits; keep it fast and safe to call multiple times. Pass `nil` to unregister the callback for this `name`.


## Returns

- original_callback
    Function. The previous callback registered under the same name. Returns `nil` if none existed, which you can use to restore the old callback if needed.


## Description

> Callbacks registered with `register_atexit` run when the script exits, including when the user stops it with the **volume buttons**, and they execute before Lua performs garbage collection.
> Callbacks registered under different names have no guaranteed execution order; if you need ordered execution, orchestrate it inside a single callback.
> Keep callback work short to avoid delaying the exit experience.
> This function is available only in versions released after 2025-07-05.


## Example

```lua
register_atexit("cleanup", function()
    sys.toast("Clean up resources before exit")
    sys.msleep(300)
end)

while true do
    sys.toast("Try stopping the script with the volume key\n" .. os.date("%Y-%m-%d %H:%M:%S"))
    sys.msleep(1000)
end
```
**Note**: Uses [`sys.toast`](/en/docs/handbook/sys/sys.toast.md), [`sys.msleep`](/en/docs/handbook/sys/sys.msleep.md)

---

Source: [Run image inference with a CoreML Vision request (:predict)](https://xxtouch.app/en/docs/handbook/coreml/coreml_vision_request_objectm_predict.md)
Path: handbook/coreml/coreml_vision_request_objectm_predict.md

# Run image inference with a CoreML Vision request (:predict)

## Declaration

```lua
result, err = vision_request:predict(image)
```

or

```lua
submitted, err = vision_request:predict(image, {
    async = is_async,
    multi_array_output = "table" or "MLMultiArray",
    uses_cpu_only = cpu_only_for_this_call,
})
```

## Parameters

- image
  An [image object](/en/docs/handbook/image/index.md) to run inference on.

- async
  Boolean, optional. When `true`, submits the request asynchronously. Defaults to `false`.

- multi_array_output
  String, optional. When the model returns `MLMultiArray` features, choose `"table"` or `"MLMultiArray"`. Defaults to `"table"`.

- uses_cpu_only
  Boolean, optional. Applies only to this call. When `true`, this inference runs on CPU only.

## Returns

- result
  Table.
  <details>
  <summary>Object detection model return structure</summary>

  ```lua
  {
      {
          ["y"] = number_value,
          ["x"] = number_value,
          ["w"] = number_value,
          ["h"] = number_value,
          ["confidence"] = number_value(0.0 ~ 100.0),
          ["name"] = string_value,
      },
      ...
  }
  ```
  </details>

  <details>
  <summary>Image classification model return structure</summary>

  ```lua
  {
      {
          ["confidence"] = number_value(0.0 ~ 100.0),
          ["name"] = string_value,
      },
      ...
  }
  ```
  </details>

  <details>
  <summary>Other model types</summary>

  ```lua
  {
      ...
  }
  ```
  </details>

## Notes

- Available since app version 1.3.8+.
- Not supported on iOS versions below 12.
- Runs inference on the image using the current Vision request and returns the result.
- If the model returns `MLMultiArray` feature values, set `multi_array_output = "MLMultiArray"` to keep them as native tensor objects for further processing.
- `:run()` is an alias of `:predict()`. After async submission, use `:is_done()` and `:results()` to read the result.
- Vision request objects also expose methods such as `:metadata()`, `:compute_units()`, `:image_crop_and_scale_option()`, `:class_labels()`, and `:is_vision_request()`

## Example

```lua
compiled_model_path = XXT_HOME_PATH..'/models/yolo11m.mlmodelc'

file.remove(compiled_model_path)

if not file.exists(compiled_model_path) then
    local tmp_path, err = coreml.compile_model(XXT_HOME_PATH..'/models/yolo11m.mlpackage')
    if not tmp_path then
        error(err)
    end
    file.move(tmp_path, compiled_model_path, 'mo')
end

vnrequest, err = coreml.new_vision_request(compiled_model_path)
if not vnrequest then
    error(err)
end

rets = vnrequest:predict(screen.image())
nLog(rets)
```

---

Source: [Network log (nLog)](https://xxtouch.app/en/docs/handbook/develop-helper/nLog.md)
Path: handbook/develop-helper/nLog.md

# Network log (nLog)

## Declaration

```lua
nLog(text)
```

## Parameters

- text
  String. Log content.

## Description

> This is a protocol function (no-op by default). Its behavior is defined by the paired development environment.
> When debugging with the companion dev environment, this function sends the log back to the dev tool's log panel.

## Example

```lua
-- Send the print buffer back to the dev tool's log window
nLog(print.out())
```

---

Source: [Unlock screen (device.unlock_screen)](https://xxtouch.app/en/docs/handbook/device/device.unlock_screen.md)
Path: handbook/device/device.unlock_screen.md

# Unlock screen (device.unlock_screen)

## Declaration

```lua
device.unlock_screen([ password ])
```

## Parameters

- password
  String, optional. Screen lock password. Not recommended.

## Description

> Using a password to unlock only works on a full jailbreak with tweak injection enabled; not available on the TrollStore version

## Example

```lua
device.unlock_screen()
```

---

Source: [Set auto dismiss timeout (:set_timeout)](https://xxtouch.app/en/docs/handbook/dialog/dialogm_set_timeout.md)
Path: handbook/dialog/dialogm_set_timeout.md

# Set auto dismiss timeout (:set_timeout)

## Declaration

```lua
dialog_obj = dialog_obj:set_timeout(seconds[, submit])
```

## Parameters

- seconds
  Number. Auto dismiss time in seconds
- submit
  Boolean, optional. Whether timeout counts as submit. true = submit, false = cancel. Default false

## Returns

- dialog_obj
  Dialog. Returns the dialog itself

## Description

> Configure the dialog's auto dismiss time

## Example

```lua
dialog():set_timeout(3):show() -- 3s timeout, not submitted
--
dialog():set_timeout(3, true):show() -- 3s timeout, submitted
```

---

Source: [Load a table from serialized text (table.load_string)](https://xxtouch.app/en/docs/handbook/ext-table/table.load_string.md)
Path: handbook/ext-table/table.load_string.md

# Load a table from serialized text (table.load_string)

## Declaration

```lua
tab = table.load_string(text)
```

## Parameters

- text
  String. Serialized textual description of a table's tree structure. Must contain only static data, no executable code.

## Returns

- tab
  Table or nil. Returns the loaded table on success; nil on failure.

## Description

> Convert a tree-structure textual description to a table object.
> In a sense, [table.load_string](/en/docs/handbook/ext-table/table.load_string.md) is the inverse of [table.deep_dump](/en/docs/handbook/ext-table/table.deep_dump.md) (depending on cyclic references and non-table reference types).
> Unlike [load](https://www.lua.org/manual/5.3/manual.html#pdf-load), this does not execute any code in the text; only static data are used.
> For example, the following snippet contains executable code that is intentionally ignored; after running, `b` is nil because the code inside is not executed.
```lua
b = table.load_string[[ {
    a = os.execute('reboot'), -- This code will NOT run and will become nil
} ]]
```

## Example

```lua
local t = table.load_string[[ {
    a = 1,
    b = 2,
    c = 3,
} ]]
sys.alert(t.b)
```
**Note**: Uses [`sys.alert`](/en/docs/handbook/sys/sys.alert.md)

---

Source: [Get file size (file.size)](https://xxtouch.app/en/docs/handbook/file/file.size.md)
Path: handbook/file/file.size.md

# Get file size (file.size)

## Declaration

```lua
size, err = file.size(path)
```

## Parameters

- path
  String. Absolute file path.

## Returns

- size
  Integer or nil. nil if file does not exist or path is a directory; otherwise file size in bytes.
- err
  String. Error message when operation fails.

## Description

> Get the size of a file.

## Example

```lua
local fsize, err = file.size("/var/mobile/1.zip")
if fsize then
    sys.alert("/var/mobile/1.zip size: "..fsize.." bytes")
else
    sys.alert("/var/mobile/1.zip is not a file: "..err)
end
```
**Note**: Uses [`sys.alert`](/en/docs/handbook/sys/sys.alert.md)

---

Source: [Execute an FTP command (ftp.cmd)](https://xxtouch.app/en/docs/handbook/ftp/ftp.cmd.md)
Path: handbook/ftp/ftp.cmd.md

# Execute an FTP command (ftp.cmd)

## Declaration

```lua
result, err = ftp.cmd(URL, cmd [, connectTimeoutSec ])
```

## Parameters

- URL
    String. Remote FTP URL, including the username and password. For directory operations, use a directory URL ending in `/`.
- cmd
    String. A single FTP protocol command, such as `MKD test`. A table of commands is not supported.
- connectTimeoutSec
    Number, optional. Connection timeout in seconds. Default: 10. This does not limit the total duration of the request.

## Returns

- result
    String or nil. On success, returns the received data, which may be an empty string. With a directory URL, this is usually a directory listing, not the FTP command's status code or control connection reply. Returns nil on failure.
- err
    String or nil. On failure, a text description of the error. On success, no second value is returned, so the receiving variable is nil.

## Description

Sends a command to an FTP server for operations such as creating directories. These operations act on files or directories on the server.

The command runs before changing to the directory specified in the URL. Relative paths are based on the default directory after login; for example, `MKD uploads/test` creates test inside uploads under that directory. Do not rely on the URL path to change the command's working directory. Paths in commands are sent directly, without URL percent-decoding.

`MKD` usually creates only one directory level, so the parent directory must already exist. The operation may fail if the directory already exists, the account lacks permission, or the server does not support the command. To create multiple levels, call the function separately for each directory, from parent to child.

In the current implementation, any command text containing uppercase `LIST` or `NLST` is not sent; only the default request for the URL is performed. This also applies when those substrings occur in a directory name. Therefore, `NLST` does not switch to a names-only listing, and the arguments in `LIST -a` have no effect.

> **After executing the command, the function still requests the data at the URL; with a directory URL, it also retrieves a directory listing. If that listing or the data connection subsequently fails, the directory may already have been created, but the function still returns nil and an error message.**
> **This function may yield; other [threads](../thread/README.md) may run before it returns.**

## Simple example

> Put the username and password in the URL. The format is as follows (brackets indicate optional parts):

```lua
ftp://[user:password@]host[:port]/path
```

> If the username or password contains `@`, `:`, or `/`, escape them as `%40`, `%3A`, or `%2F`, respectively. Other characters that are invalid in a URL can be percent-encoded.
> For example, with username `havonz` and password `11@@22`, create test in the default directory after login:

```lua
local result, err = ftp.cmd("ftp://havonz:11%40%4022@192.168.31.13/", "MKD test", 10)
if result == nil then
    sys.alert("Creation failed: " .. tostring(err))
else
    sys.alert("Created successfully")
end
```

## Advanced example

Create demo and then demo/logs; neither should exist yet. Stop if any step fails. Previously created directories are not automatically deleted.

```lua
local url = "ftp://havonz:11%40%4022@192.168.31.13/"

for _, path in ipairs({ "demo", "demo/logs" }) do
    local result, err = ftp.cmd(url, "MKD " .. path, 10)
    if result == nil then
        sys.alert("Creation failed " .. path .. ": " .. tostring(err))
        return
    end
end

sys.alert("Directories created")
```

**Note**: The code above uses [`sys.alert`](../sys/sys.alert.md), a function from another chapter.

---

Source: [Release a gamepad button (:up)](https://xxtouch.app/en/docs/handbook/gamepad/gamepadm_up.md)
Path: handbook/gamepad/gamepadm_up.md

# Release a gamepad button (:up)

> **This method is available in versions after 20260805**

## Declaration

```lua
success, err = pad:up(button)
```

## Parameters

- button
  Integer or string. See [button parameters](gamepadm_down.md) for supported numbers and names

## Returns

- success
  Boolean. True if the operation succeeds; false if the device is disconnected or busy, or if input delivery fails
- err
  String. Error message when the operation fails

## Description

> Releases the specified button. Invalid argument types, unknown names, and out-of-range values raise Lua argument errors.

## Example

```lua
local pad = assert(gamepad.connect())

assert(pad:down("left_shoulder"))
assert(pad:up("left_shoulder"))
assert(pad:down(13))
assert(pad:up(13))
assert(pad:disconnect())
```

---

Source: [Send POST request (http.post)](https://xxtouch.app/en/docs/handbook/http/http.post.md)
Path: handbook/http/http.post.md

# Send POST request (http.post)

## Declaration

```lua
code, res_headers_json, body = http.post(URL [, timeout_secs, headers, data, url_no_escape])
```

## Declaration (named arguments)

**Supported since 2025-06-25; progress options are supported since 2026-04-02**
```lua
code, res_headers_json, body = http.post{
    url = URL;
    timeout = timeout_secs;
    headers = headers;
    params = query_params;

    -- The following body options are mutually exclusive, priority: multipart > data > json > upload_file
    multipart = multipart_form;
    data = body_data;
    json = body_json;
    upload_file = upload_file_path;

    download_file = save_response_body_file_path;
    progress = progress_callback;
    progress_interval_ms = progress_interval_ms;
}
```

## Parameters

- URL
  String. Request URL. The function escapes the URL by default; see "url_no_escape" if you don't want this.
- timeout_secs
  Number, optional. Timeout in seconds. Default 10.
- headers
  Table, optional. Request headers in the form `{ field1 = value1, ... }`. Default `{}`.
- query_params
  Table, optional. Query string parameters in the form `{ field1 = value1, ... }`. Default `{}`.
- body_data
  String or Table, optional. Request body.
  Since 2025-06-25, if a table is provided, it is encoded as application/x-www-form-urlencoded.
- multipart_form
  Table, optional. Multipart form data to send.
- body_json
  Table, optional. Body encoded as application/json.
- upload_file_path
  String, optional. Send file content directly as body.
- save_response_body_file_path
  String, optional. If provided, the returned body is the saved file path on success.
- progress_callback
  Function, optional. Supported since 2026-04-02. Called when upload or download progress changes. The first argument is the current progress info.
- progress_interval_ms
  Integer, optional. Supported since 2026-04-02. Progress callback interval in milliseconds.
- url_no_escape
  Boolean, optional. true = do not escape URL. Default false.
  For custom escaping, see the [`lcurl` module](/en/docs/handbook/open-source/lcurl.md) [easy:escape](https://lua-curl.github.io/lcurl/modules/lcurl.html#easy:escape) and [easy:unescape](https://lua-curl.github.io/lcurl/modules/lcurl.html#easy:unescape).

## Returns

- code
  Integer. HTTP status code. -1 on timeout.
- res_headers_json
  String or nil. Response headers in JSON. nil on timeout.
- body
  String or nil. Response body. If saved to file, this is the file path. nil on timeout.

## Description

> Send data with HTTP/1.1 POST.
> This function may yield; other [threads](/en/docs/handbook/thread/index.md) may run before it returns.
> For HTTP/1.0 or HTTP/0.9 servers you can use:
```lua
body = httpPost(URL, string_body, timeout_secs)
```

The `info` table passed to the progress callback has this structure:

```lua
{
    count_of_bytes_sent = bytes_sent;
    count_of_bytes_expected_to_send = bytes_expected_to_send;
    count_of_bytes_received = bytes_received;
    count_of_bytes_expected_to_receive = bytes_expected_to_receive;
}
```

## Example

```lua
local code, res_headers, body = http.post("https://httpbin.org/post?hello=world&你好=世界", 15, {
    ["User-Agent"] = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0)", -- simulate IE8
    ["Cookie"] = "a=1; b=2; c=3"; -- send cookies
}, "data to send")
if code == 200 then -- HTTP_OK
    sys.alert(body)
end
```
**Note**: Uses [`sys.alert`](/en/docs/handbook/sys/sys.alert.md)

## Example (named arguments)

```lua
local code, res_headers, body = http.post{
    url = "https://httpbin.org/post";
    timeout = 15;
    headers = {
        ["User-Agent"] = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0)";
        ["Cookie"] = "a=1; b=2; c=3";
    };
    params = {
        ["hello"] = "world";
        ["你好"] = "世界";
    };
    data = "data to send";
}
if code == 200 then
    sys.alert(body)
end
```
**Note**: Uses [`sys.alert`](/en/docs/handbook/sys/sys.alert.md)

## Example: submit form

```lua
local c, h, r = http.post('https://httpbin.org/post', 60, {}, 'name=alice&email=alice%40example.com')
if (c == 200) then
    sys.alert(r, 0, 'Submitted')
else
    if (c == -1) then
        sys.alert('Request failed, please check network', 0, 'Timeout')
    else
        sys.alert('Error #'..c..'\n'..r, 0, 'HTTP Error')
    end
end
```
**Note**: Uses [`sys.alert`](/en/docs/handbook/sys/sys.alert.md)

---

Source: [Merge images (image.oper_merge)](https://xxtouch.app/en/docs/handbook/image/image.oper_merge.md)
Path: handbook/image/image.oper_merge.md

# Merge images (image.oper_merge)

## Declaration

```lua
status = image.oper_merge(image_file_list, output_path, merge_type, quality)
```

## Parameters

- image_file_list
  Table (array). File names to merge; absolute paths supported
- output_path
  String. Output file path; absolute paths supported
- merge_type
  Integer. 0 = horizontal merge; 1 = vertical merge
- quality
  Number. When output format is jpg, controls quality in range 0.0 ~ 1.0

## Returns

- status
  Integer. 0 = success; 1 = failed; 2 = failed; 3 = failed

## Description

> Default image directory is /var/mobile/Media/1ferver/res. Use absolute/relative paths for custom locations

## Example

```lua
image.oper_merge({"1.png","2.png","3.png"}, "4.jpg", 0, 0.5)
```

---

Source: [Decode JSON string to Lua value (json.decode)](https://xxtouch.app/en/docs/handbook/json/json.decode.md)
Path: handbook/json/json.decode.md

# Decode JSON string to Lua value (json.decode)

## Declaration

```lua
value, err = json.decode(jsonText)
```

## Parameters

- jsonText
  String. JSON text to be converted to a Lua value/table.

## Returns

- value
  Table or String or Number or Boolean or json.null or nil. A Lua value corresponding to the JSON structure on success; otherwise nil.
- err
  String or nil. Error message when conversion fails (i.e., when value is nil).

## Description

> Converts JSON text into the corresponding Lua value.
> This function can be used in XUI.

## Example

```lua
print(json.decode('true'))
print(json.decode('17'))
print(json.decode('"哈哈"'))
print(json.decode('null'))
print(json.decode(''))
print(table.deep_dump(json.decode('{}')))
print(table.deep_dump(json.decode('{"name":"alice","hello":"world"}')))
print(table.deep_dump(json.decode('[]')))
print(table.deep_dump(json.decode('[1, 2, 3, "foo"]')))
--
sys.alert(print.out())
```
**Note**: Uses [`table.deep_dump`](/en/docs/handbook/ext-table/table.deep_dump.md), [`print.out`](/en/docs/handbook/develop-helper/print.md), [`sys.alert`](/en/docs/handbook/sys/sys.alert.md)

```lua
-- Use json.decode to convert \uXXXX Unicode escapes to text
sys.alert(json.decode([["\u4f60\u597d"]])) -- output: 你好
```
**Note**: Uses [`sys.alert`](/en/docs/handbook/sys/sys.alert.md)

---

Source: [Release a physical key (key.up)](https://xxtouch.app/en/docs/handbook/key/key.up.md)
Path: handbook/key/key.up.md

# Release a physical key (key.up)

> **The hardware keyboard behavior described on this page is available in versions after 20260805**

## Declaration

```lua
key.up(keycode)
```

## Parameters

- keycode
  String. Physical key code. See [Samples and supported key codes](/en/docs/handbook/key/samples.md).

## Description

> Simulate releasing a previously pressed physical key.

- This function remains paired with the matching `key.down`, even if the global hardware keyboard connection changes between the calls, preventing duplicate input or an incorrect release
- Without a matching `key.down`, standard keyboard and keypad keys use the current [global hardware keyboard](key.connect_global_keyboard.md). Media and vendor-defined keys keep their previous behavior
- Calls through `key(...):up()` follow the same rules

## Example

See [the consolidated examples at the end of this chapter](/en/docs/handbook/key/samples.md).

---

Source: [Press a hardware mouse button (:down)](https://xxtouch.app/en/docs/handbook/mouse/mousem_down.md)
Path: handbook/mouse/mousem_down.md

# Press a hardware mouse button (:down)

> **This method is available in versions after 20260805**


## Declaration

```lua
success, error_message = mouse_obj:down(button)
```


## Parameters

- button
  Integer or string. Pass a value from `1` through `32` or one of the button names below. Strings are case-insensitive.


## Returns

- success
  Boolean. `true` if the button is pressed successfully; otherwise `false`.
- error_message
  String. The reason the operation failed.


## Description

> Button numbers range from `1` through `32`. Values outside this range raise a Lua argument error.

| Name | Number |
|---|---:|
| `left` | 1 |
| `right` | 2 |
| `middle` | 3 |
| `back` | 4 |
| `forward` | 5 |

> Buttons 1, 2, and 3 usually represent the left, right, and middle buttons. `back` and `forward` are aliases for Buttons 4 and 5. Buttons 6 through 32 have no fixed names, and their behavior depends on iOS and the target app. Some apps may receive only the first five buttons.


## Example

```lua
local m = assert(mouse.connect())
assert(m:down("left"))
assert(m:up("left"))
assert(m:down(13))
assert(m:up(13))
assert(m:disconnect())
```

---

Source: [luaiconv (encoding conversion)](https://xxtouch.app/en/docs/handbook/open-source/luaiconv.md)
Path: handbook/open-source/luaiconv.md

# luaiconv (encoding conversion)

[luaiconv manual](https://ittner.github.io/lua-iconv/#api-documentation)

---

## Example: GBK to UTF-8

```lua
local iconv = require("iconv")
local cd = iconv.new("utf-8", "gbk") -- create a converter from GBK to UTF-8
local f = io.open("/var/mobile/1.txt", "rb")
local s = f:read("*a")
f:close()
sys.alert(cd:iconv(s))
```
**Note**: Uses [`sys.alert`](/en/docs/handbook/sys/sys.alert.md)

## Example: UTF-16LE to UTF-8

```lua
local iconv = require("iconv")
local cd = iconv.new("utf-8", "utf-16le") -- create a converter from UTF-16LE to UTF-8
local f = io.open("/var/mobile/1.txt", "rb")
local s = f:read("*a")
f:close()
sys.alert(cd:iconv(s))
```
**Note**: Uses [`sys.alert`](/en/docs/handbook/sys/sys.alert.md)

## Example: UTF-16BE to UTF-8

```lua
local iconv = require("iconv")
local cd = iconv.new("utf-8", "utf-16be") -- create a converter from UTF-16BE to UTF-8
local f = io.open("/var/mobile/1.txt", "rb")
local s = f:read("*a")
f:close()
sys.alert(cd:iconv(s))
```
**Note**: Uses [`sys.alert`](/en/docs/handbook/sys/sys.alert.md)

---

Source: [Read data from pasteboard (pasteboard.read)](https://xxtouch.app/en/docs/handbook/pasteboard/pasteboard.read.md)
Path: handbook/pasteboard/pasteboard.read.md

# Read data from pasteboard (pasteboard.read)

## Declaration

```lua
data = pasteboard.read([ uti ])
```

## Parameters

- uti
  String, optional. [Uniform Type Identifiers](https://developer.apple.com/library/ios/documentation/Miscellaneous/Reference/UTIRef/Articles/System-DeclaredUniformTypeIdentifiers.html). Default: auto-detect content type.
  When provided, forces reading with the specified UTI. If the pasteboard content cannot be read as that UTI, returns an empty string.

## Returns

- data
  String. The pasteboard content. May be text or binary data. Returns `""` (empty string) if it cannot be read as requested.

## Description

> Read content from the system pasteboard.

## Example

```lua
sys.alert("Pasteboard content: "..pasteboard.read())
--
sys.alert("Pasteboard content: "..pasteboard.read('public.text')) -- Force read as plain text even if RTF
```
**Note**: Uses [`sys.alert`](/en/docs/handbook/sys/sys.alert.md)

---

Source: [Load plist data (plist.load)](https://xxtouch.app/en/docs/handbook/plist/plist.load.md)
Path: handbook/plist/plist.load.md

# Load plist data (plist.load)

## Declaration

```lua
tab = plist.load(plistData)
```

## Parameters

- plistData
  String. The raw plist data to load.

## Returns

- tab
  Table or nil. On success, returns a table representing the plist tree; otherwise nil.

## Description

> The inverse of `plist.dump`: convert plist data into a Lua table.
> Non-generic data types are not supported and will be ignored.

## Examples

```lua
-- Example 1 (OpenStep format)
local jtmp = plist.load([[
{
    arr = (
        46,
        99,
        7,
    );
    dict = {
        a = 55;
        b = 65;
        c = 9;
    };
}
]])
sys.alert(jtmp.arr[1]) -- 46
sys.alert(jtmp.dict.c) -- 9

-- Example 2 (XML format)
local xtmp = plist.load([[
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "https://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>arr</key>
    <array>
        <string>46</string>
        <string>99</string>
        <string>7</string>
    </array>
    <key>dict</key>
    <dict>
        <key>a</key>
        <string>55</string>
        <key>b</key>
        <string>65</string>
        <key>c</key>
        <string>9</string>
    </dict>
</dict>
</plist>
]])
sys.alert(xtmp.arr[1]) -- 46
sys.alert(xtmp.dict.c) -- 9
```
**Note**: Uses [`sys.alert`](/en/docs/handbook/sys/sys.alert.md)

---

Source: [Push a value into the process queue dictionary (proc_queue_push)](https://xxtouch.app/en/docs/handbook/proc/proc_queue_push.md)
Path: handbook/proc/proc_queue_push.md

# Push a value into the process queue dictionary (proc_queue_push)

## Declaration

```lua
size = proc_queue_push(key, value)
```

## Parameters

- key
  String. The key of the queue.
- value
  String. The value to push.

## Returns

- size
  Integer. The size of the queue after pushing. If it returns 0, the push failed.

## Description

- This function is equivalent to [`proc_queue_push_back`](/en/docs/handbook/proc/proc_queue_push_back.md).
- All process queues whose names start with "xxtouch." or "1ferver." are reserved.
- The queue size must not exceed 10000. If it exceeds, the earliest values will be discarded (FIFO trimming).
- Push a value into the process queue dictionary and return the queue size.
- Empty string cannot be pushed.

## Example

```lua
local size = proc_queue_push("billnos", "name")
if size ~= 0 then
    print("has "..size.." bill(s)")
else
    print("failed")
end
```

---

Source: [Keep Screen (screen.keep)](https://xxtouch.app/en/docs/handbook/screen/screen.keep.md)
Path: handbook/screen/screen.keep.md

# Keep Screen (screen.keep)

## Declaration

```lua
screen.keep()
```

## Description

> Cache the current screen image into a buffer. When calling color picking, color finding, screenshot, image finding functions multiple times, data will be read from the cached buffer instead of the live screen, improving performance.
> This is an optimization function for heavy static image processing.
> It ONLY affects XXTouch's capture/color functions and does NOT freeze the actual device screen.

## Example

```lua
-- Loop and sample colors of 6144 points, output to log
t = {}
screen.keep()
for k = 1, 640, 10 do
    for j = 1, 960, 10 do
        -- format as hex string
        t[#t + 1] = string.format("%X", screen.get_color(k, j))
    end
end
screen.unkeep()
nLog(t)
```
**Note**: Uses [`nLog`](/en/docs/handbook/develop-helper/nLog.md)

## Tips

> - Two consecutive `screen.get_color` calls on the same position may return different values.
> - Without `screen.keep`, a single `screen.get_color` call takes about the same time as one `screen.keep` call.
> - After `screen.keep`, about 50 consecutive `screen.get_color` calls cost roughly the same as a single `screen.keep` call.

---

Source: [What Is Script Daemon Mode?](https://xxtouch.app/en/docs/handbook/supplement/daemon-mode.md)
Path: handbook/supplement/daemon-mode.md

# What Is Script Daemon Mode?

- Daemon mode ensures that if a script is terminated by external factors (e.g. service crash, power loss), it will automatically relaunch once the device returns to a normal state. Exceptions:
  - The device runs out of power and is never recharged
  - The device cannot boot
  - Jailbreak state is lost after reboot
  - The device is in Safe Mode
  - The device has a passcode and is rebooted
  - Manually terminated by user
  - Script terminated due to a runtime error
- Daemon mode launches before the boot-time script. After an unexpected reboot, you can add the following code at the beginning of your script to ensure the screen is unlocked before proceeding:
```lua
while (device.is_screen_locked()) do
  device.unlock_screen()
  sys.msleep(1000)
end
sys.toast("Screen unlocked. Script starts.")
-- Your script continues below
-- ...
```

---

Source: [Input Prompt (sys.input_box)](https://xxtouch.app/en/docs/handbook/sys/sys.input_box.md)
Path: handbook/sys/sys.input_box.md

# Input Prompt (sys.input_box)

## Description

> Pops up a system input dialog, supporting up to 3 buttons and 2 text fields. Blocks all threads until a result is returned.
> The default title is `"Script Prompt"`.
> **For versions after 2026-01-08, this function yields in a multitasking environment.**

## Examples

```lua
local text = sys.input_box("Description text")
--
local text = sys.input_box("Title", "This is the description")
--
local text = sys.input_box("Title", "This is the description", 0)
--
local text = sys.input_box("Title", "Description", "Placeholder", 0)
--
local text = sys.input_box("Title", "Description", "Placeholder", "Prefilled content", 0)
--
local text = sys.input_box("Title", "Description", "Placeholder", "Prefilled content", "Default button title", 0)
--
local text, choice = sys.input_box("Title", "Description", "Placeholder", "Prefilled content", "Default button", "Button1", 0)
--
local text, choice = sys.input_box("Title", "Description", "Placeholder", "Prefilled content", "Default button", "Button1", "Button2", 0)
--
local text1, text2 = sys.input_box("Title", "Description", {"Field1 placeholder", "Field2 placeholder"}, 0)
--
local text1, text2 = sys.input_box("Title", "Description", {"Field1 placeholder", "Field2 placeholder"}, {"Field1 content", "Field2 content"}, 0)
--
local text1, text2, choice = sys.input_box("Title", "Description", {"Field1 placeholder", "Field2 placeholder"}, {"Field1 content", "Field2 content"}, "Default button", "Button1", "Button2", 0)
```

---

Source: [HID event messages](https://xxtouch.app/en/docs/handbook/system-callback/hid.md)
Path: handbook/system-callback/hid.md

# HID event messages

## Declaration

```lua
thread.register_event("xxtouch.hid_event", function(val)
    local event = json.decode(val)
    if event.event_type=="touch" then
        if event.event_name=="touch.on" then
            sys.toast("Touch down at: ("..event.x..", "..event.y..")\n"..event.time)
        elseif event.event_name=="touch.move" then
            sys.toast("Touch moved to: ("..event.x..", "..event.y..")\n"..event.time)
        elseif event.event_name=="touch.off" then
            sys.toast("Touch up at: ("..event.x..", "..event.y..")\n"..event.time)
        end
    else
        if event.event_name=="key.down" then
            sys.toast("Key down: "..event.key_name.."\n"..event.time)
        elseif event.event_name=="key.up" then
            sys.toast("Key up: "..event.key_name.."\n"..event.time)
        end
    end
end)
```

## State

- val
  If listening is registered, all HID event info will be delivered here. This severely impacts script performance; unregister it promptly when no longer needed.
  All touch coordinates in HID events use the portrait coordinate system with the Home button at the bottom. If needed, convert using [screen.rotate_xy](/en/docs/handbook/screen/screen.rotate_xy.md).

## Example

```lua
-- Clear message queue
proc_queue_clear("xxtouch.hid_event")
--
-- Start listening
local eid = thread.register_event("xxtouch.hid_event", function(val)
    local event = json.decode(val)
    if event.event_type=="touch" then
        if event.event_name=="touch.on" then
            sys.toast("Touch down at: ("..event.x..", "..event.y..")\n"..event.time)
        elseif event.event_name=="touch.move" then
            sys.toast("Touch moved to: ("..event.x..", "..event.y..")\n"..event.time)
        elseif event.event_name=="touch.off" then
            sys.toast("Touch up at: ("..event.x..", "..event.y..")\n"..event.time)
        end
    else
        if event.event_name=="key.down" then
            sys.toast("Key down: "..event.key_name.."\n"..event.time)
        elseif event.event_name=="key.up" then
            sys.toast("Key up: "..event.key_name.."\n"..event.time)
        end
    end
end)
--
touch.on(100, 100):off()
sys.msleep(1000)
key.press('homebutton')
--
sys.msleep(20000) -- wait 20 seconds
--
-- Unregister callback; without unregistering, the script will not end here
thread.unregister_event("xxtouch.hid_event", eid)
```
**Note**: Uses [`sys.toast`](/en/docs/handbook/sys/sys.toast.md), [`sys.msleep`](/en/docs/handbook/sys/sys.msleep.md), [`proc_queue_clear`](/en/docs/handbook/proc/proc_queue_clear.md), [`thread.register_event`](/en/docs/handbook/thread/thread.register_event.md), [`thread.unregister_event`](/en/docs/handbook/thread/thread.unregister_event.md)

---

Source: [Remove a task from the queue (thread.kill)](https://xxtouch.app/en/docs/handbook/thread/thread.kill.md)
Path: handbook/thread/thread.kill.md

# Remove a task from the queue (thread.kill)

## Declaration

```lua
thread.kill(task_id)
```

## Parameters

- task_id
  Integer.

## Description

Remove a task from the queue, regardless of whether it has started or completed.

## Example

See [the consolidated examples at the end of this chapter](/en/docs/handbook/thread/samples.md)

---

Source: [! Move finger on screen (:move)](https://xxtouch.app/en/docs/handbook/touch/touchm_move.md)
Path: handbook/touch/touchm_move.md

# ! Move finger on screen (:move)

## Declaration

```lua
te = te:move(x, y)
```

## Parameters

- x, y
  Integers. Target coordinates in the current rotated coordinate system.

## Returns

- te
  Touch event object itself. You can get a touch event object via [`touch.on`](/en/docs/handbook/touch/touch.on.md).

## Description

> Simulate moving the finger from current position to another position.
> Coordinate parameters follow the coordinate system initialized via [`screen.init`](/en/docs/handbook/screen/screen.init.md).
> This method may yield; other [threads](/en/docs/handbook/thread/index.md) may run before it returns.
> You can also call it in the following forms (finger ID must be 1 ~ 29):
```lua
touch.move(finger_id, x, y)
touch.move(finger_id, x, y, pressure)
```
> The above calls differ from the `:move` method in that they move immediately to the target without stepping.

## Example

```lua
-- Touch at 100,100 then slide to 200,200 and lift
touch.on(100, 100):move(200, 200):off()

-- Another usage
touch.on(1, 100, 100) -- finger #1 touches at 100,100
for i=1, 100 do       -- move finger #1 step by step to 100,200
    touch.move(1, 100, 100 + i)
end
touch.off(1)          -- lift finger #1
```

---

Source: [Common Options](https://xxtouch.app/en/docs/handbook/ui_element/options.md)
Path: handbook/ui_element/options.md

# Common Options

> **This module is available in versions after 20260507**

Several `ui_element` APIs accept an options table for target app, result count, child depth, hit checks, and action steps.

## Query Options

```lua
local options = {
    pid = app.front_pid(),
    max_level = 2,
    max_elements = 200,
    include_hit_state = true,
}
```

- pid
  Integer. Target app process identifier. When omitted, the foreground app is usually used.
- max_level
  Integer. Child expansion depth. Use `1` or `2` to keep returned data small.
- max_elements
  Integer. Maximum number of top-level elements to return.
- fallback_children
  Boolean. Try reading child elements when the regular list is empty. Default depends on the API.
- include_hit_state
  Boolean. Include hit state fields.
- hit_test
  Boolean. Enable screen-sampling hit lookup. Normal scripts usually do not need it.
- fallback_hit_test
  Boolean. Try screen-sampling hit lookup when the regular list is empty.
- hit_test_spacing
  Number. Screen-sampling spacing in logical coordinates. Default `40`.

### Attribute Exclusion Options {#attribute-exclusions}

**Available from 20261115**. Only for `snapshot()` and `list_text_elements()`. All are booleans, default to `false`, and also apply to child elements. When these states are not needed, enabling the exclusion options can reduce query overhead and speed up snapshot capture.

- exclude_visibility
    When `true`, skip visibility queries and omit `isVisible`.
- exclude_map
    When `true`, skip map-state checks and omit `isMap`; map elements are retained.
- exclude_hit_state
    When `true`, skip center-point hit checks and omit `canHit`, `hitVerified`, `hitTestPoint`, and `hitTestPointLogical`. Cannot be combined with `include_hit_state = true`.

The element scope, text, coordinates, and supplementary element discovery rules for `hit_test` / `fallback_hit_test` are unchanged. Do not exclude a state field if you need to filter by it.

## Action Options

- point
  Table. Coordinate point used for scroll or hit lookup, for example `{ x = 200, y = 700 }`, in physical pixels.
- x / y
  Integer. Same as `point`, placed directly in the options table.
- steps
  Number. Step parameter for scroll, increase, or decrease. The actual effect depends on the target control.

## Description

> `list_text_elements()` keeps conservative defaults for old scripts.
> `find()`, `find_all()`, `snapshot()`, and action APIs are usually better for new scripts.
> `hit_test` may return elements closer to the current top layer, but it costs more. Use it only when regular queries cannot find the target.

---

Source: [Encode Text to QR Image (utils.qr_encode)](https://xxtouch.app/en/docs/handbook/utils/utils.qr_encode.md)
Path: handbook/utils/utils.qr_encode.md

# Encode Text to QR Image (utils.qr_encode)

## Declaration

```lua
img = utils.qr_encode(text[, {
    size = size,
    fill_color = fill_color,
    shadow_color = shadow_color,
}])
```

## Parameters

- text
  String. Text to encode.
- size
  Integer. Side length of the QR image. Default: 320.
- fill_color
  Integer. Fill color. Default: 0xff000000 (black, opaque).
- shadow_color
  Integer. Shadow color. Default: 0x00000000 (fully transparent).

## Returns

- img
  Image object. The generated QR image with transparent background (0x00000000).

## Examples

- Generate a 320px blue QR with transparent background and save to album
```lua
local img = utils.qr_encode("https://www.xxtouch.app", {
    size = 320,
    fill_color = 0xff409bff,
    shadow_color = 0xff308bef,
})
img:save_to_album()
```
Note: uses [`:save_to_album`](/en/docs/handbook/image/imagem_save_to_album.md)

- If some apps cannot recognize QR with transparent/dark background, replace background to white via [`:replace_color`](/en/docs/handbook/image/imagem_replace_color.md):
```lua
local img = utils.qr_encode("https://www.xxtouch.app", {
    size = 320,
    fill_color = 0xff000000,
})
img:replace_color(0x00000000, 0xffffffff)
img:save_to_album()
```
Note: uses [`:replace_color`](/en/docs/handbook/image/imagem_replace_color.md), [`:save_to_album`](/en/docs/handbook/image/imagem_save_to_album.md)

---

Source: [Select a VPN profile (vpnconf.select)](https://xxtouch.app/en/docs/handbook/vpnconf/vpnconf.select.md)
Path: handbook/vpnconf/vpnconf.select.md

# Select a VPN profile (vpnconf.select)

## Declaration

```lua
ok = vpnconf.select(nameOrId)
```

## Parameters

- nameOrId
  String. Display name or VPNID. If multiple profiles share the same name, selection is not deterministic. Use VPNID for precise selection.

## Returns

- ok
  Boolean. true on success; false on failure (usually because the specified profile does not exist).

## Description

> You can obtain VPNID via [vpnconf.list](/en/docs/handbook/vpnconf/vpnconf.list.md).

## Example

```lua
local success = vpnconf.select('DemoVPN')
if success then
    sys.alert('Operation succeeded')
else
    sys.alert('Operation failed. Please verify the target VPN exists.')
end
```

---

Source: [Evaluate JS on a webview (webview.eval)](https://xxtouch.app/en/docs/handbook/webview/webview.eval.md)
Path: handbook/webview/webview.eval.md

# Evaluate JS on a webview (webview.eval)

## Declaration

```lua
str = webview.eval(js [, id ])
```

## Parameters

- js
  String. The JavaScript code to execute.
- id
  Integer. Optional. Current webview id (1 ~ 1000). Default 1.

## Returns

- str
  String. Return value produced by the executed JavaScript.

## Description

Execute a piece of JavaScript on a webview and get the string result.

## Example

```lua
r = webview.eval("a = 3; b = 2; a * b;")
```

---

Source: [Get resource path inside current script bundle (xpp.resource_path)](https://xxtouch.app/en/docs/handbook/xpp/xpp.resource_path.md)
Path: handbook/xpp/xpp.resource_path.md

# Get resource path inside current script bundle (xpp.resource_path)

## Declaration

```lua
res_path = xpp.resource_path(filename)
```

## Parameters

- filename
  String. The resource file name to look up.

## Returns

- res_path
  String | nil. Path to the specified resource inside the current script bundle; nil if the resource does not exist.

## Description

> Get the path of a resource file inside the currently running script bundle. Localization is supported.
> See XPP spec: [XPP](/en/docs/XPP/index.md)

## Example

```lua
local path = xpp.resource_path('appicon.png')
```

---

Source: [Show a configuration UI (xui.show)](https://xxtouch.app/en/docs/handbook/xui/xui.show.md)
Path: handbook/xui/xui.show.md

# Show a configuration UI (xui.show)

## Declaration

```lua
xui.show(filename)
```

## Parameters

- filename
  String. The .xui file name within the current Script Bundle to present. Only files within the current package are allowed.

## Description

> Immediately invoke the App to present the specified configuration UI.
> This function is non-blocking and has no return value. If the UI fails to present, the error message is shown inside the App.
> See the [XUI](/XUI/README.md) specification.

## Example

```lua
xui.show('interface.xui')
```

---

Source: [Get app plugin info (app.plugin_info)](https://xxtouch.app/en/docs/handbook/app/app.plugin_info.md)
Path: handbook/app/app.plugin_info.md

# Get app plugin info (app.plugin_info)

## Declaration

```lua
info = app.plugin_info(bid)
```

## Parameters

- bid
  String. App bundle identifier. You can find it in `XXT App -> More -> App List`.

## Returns

- info
  Table. Plugin info presented as a list like `{{bid = "xxx", bundle_path = "xxx", data_path = "xxx"}, ...}`. Empty table if not exists.


## Example

```lua
local info = app.plugin_info("com.tencent.mqq") -- get QQ's plugin info
nLog(info)
```

---

Source: [Clear system caches (clear.caches)](https://xxtouch.app/en/docs/handbook/clear/clear.caches.md)
Path: handbook/clear/clear.caches.md

# Clear system caches (clear.caches)

## Declaration

```lua
clear.caches()
```

## Description

> Clear system caches. The system noticeably stalls during the call, and all threads are blocked throughout.
> This function may take a long time; force-stopping the script mid-run can be slow (it may require a hard kill).

## Example

```lua
clear.caches()
--
clear.caches{no_uicache = true} -- Skip uicache (which is slow). You may run os.execute('su mobile -c uicache') instead.
```

---

Source: [Run code when the script is terminated](https://xxtouch.app/en/docs/handbook/control-flow/terminate-callback.md)
Path: handbook/control-flow/terminate-callback.md

# Run code when the script is terminated

## Description

> This is not a specific function, but a pattern that leverages Lua's garbage-collection mechanism to run code when the script ends (or is terminated).
> > **How it works**: define a global object (a table) and attach a **finalizer** to it. When the Lua VM shuts down, the finalizers of all Lua objects (including this one) are invoked. In Lua, a finalizer is the object's [`__gc` metamethod](https://www.lua.org/manual/5.3/manual.html#2.4).

## Minimal example

```lua
-- keywords: terminate callback, on-exit
SOME_VAR = {}
setmetatable(SOME_VAR, {
    __gc = function(...)
        sys.toast('Terminated!')
        sys.msleep(500)
    end
})
--
while (true) do
    sys.toast("You can try terminating the script now\n\n"..os.date("%Y-%m-%d %H:%M:%S"))
    sys.msleep(1000)
end
```
**Note**: Uses [`sys.toast`](/en/docs/handbook/sys/sys.toast.md), [`sys.msleep`](/en/docs/handbook/sys/sys.msleep.md), [setmetatable](https://www.lua.org/manual/5.3/manual.html#pdf-setmetatable)

## Full helper example

```lua
function atexit(callback) -- Register a function to run when the script ends; avoid long operations here.
    ____atexit_guard____ = ____atexit_guard____ or {}
    if type(____atexit_guard____) == 'table' then
        if not getmetatable(____atexit_guard____) then
            setmetatable(____atexit_guard____, {
                __gc = function(self)
                    if type(self.callback) == 'function' then
                        pcall(self.callback)
                    end
                end
            })
        end
        ____atexit_guard____.callback = callback
    else
        error('Do not name your variable `____atexit_guard____`.')
    end
end
-- Copy the above to the top of your script; usage below
--
-- Register an on-exit callback
atexit(function()
    sys.toast('Terminated!')
    sys.msleep(500)
end)
--
while (true) do
    sys.toast("You can try terminating the script now\n\n"..os.date("%Y-%m-%d %H:%M:%S"))
    sys.msleep(1000)
end
```
**Note**: Uses [`sys.toast`](/en/docs/handbook/sys/sys.toast.md), [`sys.msleep`](/en/docs/handbook/sys/sys.msleep.md), [setmetatable](https://www.lua.org/manual/5.3/manual.html#pdf-setmetatable)

---

Source: [Create a general-purpose CoreML request (coreml.new_model_request)](https://xxtouch.app/en/docs/handbook/coreml/coreml.new_model_request.md)
Path: handbook/coreml/coreml.new_model_request.md

# Create a general-purpose CoreML request (coreml.new_model_request)

`coreml.new_model_request` loads a compiled CoreML model and creates a general-purpose request object that does not depend on Vision.
It is suitable for text models, tensor-input models, multi-input/multi-output models, embedding models, and any model whose input is not simply a regular image flowing through Vision.

If the model is primarily an image-recognition workflow and you want to pass an `image` object directly into a Vision pipeline, prefer `new_vision_request`.
If you need to prepare input features yourself, or the model expects `MLMultiArray`, token IDs, or multiple named inputs, this is the correct API.

`coreml.session(...)` is an alias of this function.

## Declaration

```lua
request, err = coreml.new_model_request(compiled_model_path)
```

or

```lua
request, err = coreml.new_model_request({
    compiled_model_path = compiled_model_path,
    uses_cpu_only = use_cpu_only,
    compute_units = compute_units,
})
```

## Parameters

- `compiled_model_path`
    String. Path to a compiled `.mlmodelc` model directory.

- `uses_cpu_only`
    Boolean, optional. Whether to use CPU only by default. Defaults to `false`.

- `compute_units`
    String, optional. Effective on **iOS 12+**. Supported values:
    - `"all"`
    - `"cpu_only"` or `"cpu"`
    - `"cpu_and_gpu"` or `"gpu"`
    - `"cpu_and_neural_engine"`, `"ane"`, or `"neural_engine"` (**iOS 16+**)

    When `uses_cpu_only = true`, CPU-only execution takes precedence.

## Returns

- request
    A general-purpose CoreML request object, or `nil` on failure.

- err
    String. `nil` on success; error message on failure.

## Notes

> **This function is available in versions released after 20260319**

- The base capability is available on **iOS 11+**
- `compute_units` configuration requires **iOS 12+**
- If the model declares an image feature and you want to pass an `image_object` directly into this general-purpose request, that requires **iOS 13+**
- Inputs must be passed as a table keyed by input name, for example `{ input_ids = ids }`
- Input values can be numbers, strings, booleans, dictionaries, `MLMultiArray`, and `image` objects when the model declares an image feature input
- This object only runs model inference. Image preprocessing and text tokenization should be prepared separately in Lua
- The same request object can be reused across repeated `predict()` / `run()` calls
- If older devices or some models are unstable on the default backend, you can set `uses_cpu_only = true` during creation

## Type checks

### Declaration

```lua
is_request = coreml.is_model_request(value)
```

or

```lua
is_request = coreml.is_session(value)
```

### Parameters

- value
    Any value to test.

### Returns

- is_request
    Boolean. Returns `true` if the value is a general-purpose CoreML request object.

### Notes

- `coreml.is_session()` and `coreml.is_model_request()` are equivalent aliases
- Useful in generic Lua wrappers for type guarding and argument validation
- If you already know the value came from `new_model_request(...)` / `session(...)`, you usually do not need this check

## Example

```lua
local compiled_model_path = XXT_HOME_PATH.."/models/demo_text.mlmodelc"

local req, err = coreml.new_model_request({
    compiled_model_path = compiled_model_path,
    uses_cpu_only = false,
    compute_units = "all",
})
if not req then
    error(err)
end

local out = assert(req:predict({
    input_ids = ids,
}))

print(req:input_names())
print(req:output_names())
print(out[1])
```

---

Source: [Get jailbreak-root path for a system-root path (jbroot)](https://xxtouch.app/en/docs/handbook/develop-helper/jbroot.md)
Path: handbook/develop-helper/jbroot.md

# Get jailbreak-root path for a system-root path (jbroot)

## Declaration

```lua
jbPath = jbroot(sysRootPath)
```

## Parameters

- sysRootPath
  String. A path under the system root.

## Returns

- jbPath
  String. The jailbreak-root path corresponding to `sysRootPath`.

## Description

> On roothide and rootless editions of XXTouch, this returns an absolute path that accesses the specified path under the jailbreak root.
> On rootful or TrollStore editions, this simply returns the input parameter.
> **Available since version 1.3.8 or later.**

## Example

```lua
nLog(jbroot('/')) -- /var/containers/Bundle/Application/.jbroot-XXXXXXXXXXXXXXXX/
```

---

Source: [Is screen locked (device.is_screen_locked)](https://xxtouch.app/en/docs/handbook/device/device.is_screen_locked.md)
Path: handbook/device/device.is_screen_locked.md

# Is screen locked (device.is_screen_locked)

## Declaration

```lua
locked = device.is_screen_locked()
```

## Returns

- locked
  Boolean. Whether the screen is locked

## Description

> Check whether the screen is currently locked

## Example

```lua
if device.is_screen_locked() then
    -- screen is locked
else
    -- screen is unlocked
end
```

---

Source: [Set dialog title (:set_title)](https://xxtouch.app/en/docs/handbook/dialog/dialogm_set_title.md)
Path: handbook/dialog/dialogm_set_title.md

# Set dialog title (:set_title)

## Declaration

```lua
dialog_obj = dialog_obj:set_title(title)
```

## Parameters

- title
  String. Dialog title text

## Returns

- dialog_obj
  Dialog. Returns the dialog itself

## Description

> Set the dialog's title

## Example

```lua
dialog():set_title('Title'):show()
```

---

Source: [Read all data from a file (file.reads)](https://xxtouch.app/en/docs/handbook/file/file.reads.md)
Path: handbook/file/file.reads.md

# Read all data from a file (file.reads)

## Declaration

```lua
data, err = file.reads(path)
```

## Parameters

- path
  String. Absolute file path.

## Returns

- data
  String or nil. nil if file does not exist; otherwise the entire file contents.
- err
  String. Error message when operation fails.

## Description

> Read all data from a file.

## Example

```lua
local data, err = file.reads("/var/mobile/1.zip")
if data then
    sys.alert("/var/mobile/1.zip size: "..#data.." bytes")
else
    sys.alert("Read failed: "..err)
end
```
**Note**: Uses [`sys.alert`](/en/docs/handbook/sys/sys.alert.md)

---

Source: [! Press a gamepad button (:press)](https://xxtouch.app/en/docs/handbook/gamepad/gamepadm_press.md)
Path: handbook/gamepad/gamepadm_press.md

# ! Press a gamepad button (:press)

> **This method is available in versions after 20260805**

## Declaration

```lua
success, err = pad:press(button [, press_delay_ms])
```

## Parameters

- button
  Integer or string. See [button parameters](gamepadm_down.md) for supported numbers and names
- press_delay_ms
  Finite non-negative number, optional. Time to hold the button, in milliseconds. Defaults to 60

## Returns

- success
  Boolean. True if the button was pressed and released; false if the device is disconnected or busy, the target button is already held, or input delivery fails
- err
  String. Error message when the operation fails

## Description

- Presses and releases only the target button without changing any other buttons that are already held
- The call fails if the target button is already held
- `press` yields the current Lua execution thread while waiting for the hold time. During this period, other operations on the same gamepad return `false, "hardware gamepad is busy"`; different gamepad objects remain independent
- Invalid argument types, unknown names, and out-of-range values raise Lua argument errors

## Example

```lua
local pad = assert(gamepad.connect())

assert(pad:press("a"))
assert(pad:press("menu"))
assert(pad:press(32))
assert(pad:disconnect())
```

---

Source: [Download file over HTTP (http.download)](https://xxtouch.app/en/docs/handbook/http/http.download.md)
Path: handbook/http/http.download.md

# Download file over HTTP (http.download)

## Declaration

```lua
done, info = http.download(URL, local_path [, connect_timeout_secs, resume, on_chunk, buffer_size ])
```

## Parameters

- URL
  String. Remote file URL.
- local_path
  String. Local file path to save.
- connect_timeout_secs
  Number, optional. Connection timeout in seconds. Default 10.
- resume
  Boolean, optional. Enable resume. Default false.
- on_chunk
  Function, optional. Called for each chunk; receives current info and returns true to abort.
- buffer_size
  Integer, optional. Buffer size in bytes. Default auto.

## Returns

- done
  Boolean. Whether connection and download succeeded.
- info
  Table or String. Info table on success, otherwise error message string.

## Description

```lua
-- Structure of the info table
{
    resource_size = total remote bytes,
    start_pos = start position of this download,
    size_download = bytes downloaded this time,
    speed_download = average speed (bytes/sec),
}
```
> Suited for large files; stopping the script during transfer may be slow.
> This function may yield; other [threads](/en/docs/handbook/thread/index.md) may run before it returns.

## Simple example

```lua
local done, info = http.download("https://192.168.31.13/1.zip", "/var/mobile/1.zip")
if (done) then
    sys.alert("Download complete")
else
    sys.alert("Connection failed: "..info)
end
```

## Advanced example

```lua
local done, info = http.download("https://192.168.31.13/1.zip", "/var/mobile/1.zip", 10, true, function(binfo)
    local percent = math.floor(((binfo.start_pos + binfo.size_download) / binfo.resource_size) * 100)
    sys.toast("Progress "..percent.."%")
end, 4096 * 1024)
--
if (done) then
    if (info.start_pos + info.size_download < info.resource_size) then
        sys.alert(
            "Download interrupted\nDownloaded "..info.size_download.." bytes"
            .."\nStarted at "..info.start_pos
            .."\nAvg speed "..math.floor(info.speed_download/1024).." kB/s"
            .."\nRemaining "..(info.resource_size - (info.start_pos + info.size_download)).." bytes"
        )
    else
        sys.alert(
            "Download complete\nDownloaded "..info.size_download.." bytes"
            .."\nStarted at "..info.start_pos
            .."\nAvg speed "..math.floor(info.speed_download/1024).." kB/s"
        )
    end
else
    sys.alert("Connection failed: "..info)
end
```
**Note**: Uses [`sys.alert`](/en/docs/handbook/sys/sys.alert.md), [`sys.toast`](/en/docs/handbook/sys/sys.toast.md)

## Error reference

- Requested range was not delivered by the server: the server may not support resume; set resume to false.

---

Source: [Create an image from text (image.new_text_image)](https://xxtouch.app/en/docs/handbook/image/image.new_text_image.md)
Path: handbook/image/image.new_text_image.md

# Create an image from text (image.new_text_image)

## Declaration

```lua
img = image.new_text_image(text[, {
  font = font_name,
  size = font_size,
  color = font_color,
  alpha = font_alpha,
  back_color = background_color,
  back_alpha = background_alpha,
}])
```

## Parameters

- text
  String. Text content to render
- font
  String, optional. Font family. Default "Arial"
- font_size
  Number, optional. Font size. Default 20.0
- font_color
  Integer, optional. Font color. Default 0xffffff (white)
- font_alpha
  Integer, optional. Font opacity, range 0~255. Default 255
- background_color
  Integer, optional. Background color. Default 0x000000 (black)
- background_alpha
  Integer, optional. Background opacity, range 0~255. Default 255

## Returns

- img
  Image object. The newly created image

## Description

> Create a properly sized image and render the text on it
> This call creates a new image object. For efficient frequent usage, please pair with [image:destroy](/en/docs/handbook/image/imagem_destroy.md)

---

Source: [NULL constant in JSON (json.null)](https://xxtouch.app/en/docs/handbook/json/json.null.md)
Path: handbook/json/json.null.md

# NULL constant in JSON (json.null)

## Declaration

```lua
json.null
```

## Description

> This is not a function, but a constant. When printed as text it appears like "`userdata: 0x0`".
> It represents the JSON `null` value.
> Why is it necessary? Because `nil` in a Lua table means absence; when encoding to JSON, a key with `nil` disappears. A specific sentinel is needed to represent JSON `null`.
> This value can be used in XUI.

## Example

```lua
local tb = json.decode('{"nullvalue":null}')
if tb['nullvalue'] == json.null then
    sys.alert(json.null)
end
```
**Note**: Uses [`sys.alert`](/en/docs/handbook/sys/sys.alert.md)

---

Source: [! Type text via key events (key.send_text)](https://xxtouch.app/en/docs/handbook/key/key.send_text.md)
Path: handbook/key/key.send_text.md

# ! Type text via key events (key.send_text)

> **The hardware keyboard behavior described on this page is available in versions after 20260805**

## Declaration

```lua
key.send_text(text [, per_key_delay_ms, shift_delay_ms])
```

## Parameters

- text
  String. Text to type. Only English letters, digits, spaces, half-width symbols, and escape sequences `"\b"`, `"\r"`, and `"\t"` are supported.
- per_key_delay_ms
  Integer. Delay between key events in milliseconds. Default: no delay, so input is sent as fast as the device allows.
- shift_delay_ms
  Integer. Delay for Shift in milliseconds. Uppercase letters and some symbols require holding Shift; for example, `@` is `Shift + 2`.

## Description

> This function is useful when `sys.input_text` is ineffective; it forces text input by simulating key events.

- After a [global hardware keyboard](key.connect_global_keyboard.md) is connected, text is entered through that object. Without one, the previous behavior is preserved.
- The hardware keyboard generates key and Shift combinations from the current Lua US keyboard mapping. The resulting characters are still affected by the target system's keyboard layout.
- When entered through the hardware keyboard, keys that were already held before the call are preserved. Failed input is not retried through the previous input method.

## Examples

```lua
key.send_text("AbC12#") -- type as fast as possible
--
key.send_text("AbC12#", 300) -- 300 ms delay between each key
```

---

Source: [Release a hardware mouse button (:up)](https://xxtouch.app/en/docs/handbook/mouse/mousem_up.md)
Path: handbook/mouse/mousem_up.md

# Release a hardware mouse button (:up)

> **This method is available in versions after 20260805**


## Declaration

```lua
success, error_message = mouse_obj:up(button)
```


## Parameters

- button
  Integer or string. Pass a value from `1` through `32` or a predefined button name. See the [`:down` button description](mousem_down.md).


## Returns

- success
  Boolean. `true` if the button is released successfully; otherwise `false`.
- error_message
  String. The reason the operation failed.


## Description

> Release the specified hardware mouse button.


## Example

```lua
local m = assert(mouse.connect())
assert(m:down("left"))
assert(m:up("left"))
assert(m:down(13))
assert(m:up(13))
assert(m:disconnect())
```

---

Source: [lpeg](https://xxtouch.app/en/docs/handbook/open-source/lpeg.md)
Path: handbook/open-source/lpeg.md

# lpeg

[lpeg manual](https://www.inf.puc-rio.br/~roberto/lpeg/lpeg.html)

---

---

Source: [Clear pasteboard (pasteboard.clear)](https://xxtouch.app/en/docs/handbook/pasteboard/pasteboard.clear.md)
Path: handbook/pasteboard/pasteboard.clear.md

# Clear pasteboard (pasteboard.clear)

## Declaration

```lua
items = pasteboard.clear()
```

## Returns

- items
  Table. Returns the previous pasteboard content. It may contain multiple entries, each with `type` and `data` fields.

  <details>
  <summary>Structure of the returned items</summary>

  ```lua
  {
      {
          type = "public.utf8-plain-text",
          data = "data here",
      },
      {
          type = "public.rtf",
          data = "data here",
      },
      {
          type = "public.html",
          data = "data here",
      },
      ...
  }
  ```
  </details>

## Description

> Clear the system pasteboard.
> **Available since version 1.3.8 or later.**

## Example

```lua
pasteboard.clear() -- clear pasteboard
```

---

Source: [Dump a Lua table to plist data (plist.dump)](https://xxtouch.app/en/docs/handbook/plist/plist.dump.md)
Path: handbook/plist/plist.dump.md

# Dump a Lua table to plist data (plist.dump)

## Declaration

```lua
plistData = plist.dump(tab [, format])
```

## Parameters

- tab
  Table. The Lua table to convert to plist data.
- format
  String, optional. One of "binary", "XML", or "openstep". Default: "XML".

## Returns

- plistData
  String or nil. The converted plist data on success; nil on failure.

## Description

> The inverse of `plist.load`: convert a Lua table to plist data.

## Example

```lua
local tab = {
    arr = {
        46,
        99,
        7,
    };
    dict = {
        a = 55;
        b = 65;
        c = 9;
    };
}
--
local xplist = plist.dump(tab)
sys.alert(xplist) -- XML format plist data
--
local bplist = plist.dump(tab, "binary")
sys.alert(bplist) -- Binary plist; printing will look garbled
```
**Note**: Uses [`sys.alert`](/en/docs/handbook/sys/sys.alert.md)

---

Source: [Pop a value from process queue (proc_queue_pop)](https://xxtouch.app/en/docs/handbook/proc/proc_queue_pop.md)
Path: handbook/proc/proc_queue_pop.md

# Pop a value from process queue (proc_queue_pop)

## Declaration

```lua
value = proc_queue_pop(key)
```

## Parameters

- key
  String.

## Returns

- value
  String. The popped value. If the queue does not exist or is empty, returns empty string.

## Description

- This function is equivalent to [`proc_queue_pop_front`](/en/docs/handbook/proc/proc_queue_pop_front.md).
- All process queues whose names start with "xxtouch." or "1ferver." are reserved.
- Pop a value.

## Example

```lua
local billno = proc_queue_pop("billnos")
if billno ~= "" then
    print(billno)
else
    print("no bill")
end
```

---

Source: [Unkeep Screen (screen.unkeep)](https://xxtouch.app/en/docs/handbook/screen/screen.unkeep.md)
Path: handbook/screen/screen.unkeep.md

# Unkeep Screen (screen.unkeep)

## Declaration

```lua
screen.unkeep()
```

## Description

> Cancel the effect of [`screen.keep`](/en/docs/handbook/screen/screen.keep.md) and release the cached screen image from memory.

## Example

See the example in [`screen.keep`](/en/docs/handbook/screen/screen.keep.md).

---

Source: [Notes on Boot-Time Launch](https://xxtouch.app/en/docs/handbook/supplement/bootstrap.md)
Path: handbook/supplement/bootstrap.md

# Notes on Boot-Time Launch

- Boot-time scripts start only after the home screen is fully ready; generally there will be a short delay after boot.
- Common situations where boot-time launch may not occur:
  - Cannot enter the home screen
  - Enters Safe Mode after boot
  - A lock screen passcode is set

---

Source: [Input Text (sys.input_text)](https://xxtouch.app/en/docs/handbook/sys/sys.input_text.md)
Path: handbook/sys/sys.input_text.md

# Input Text (sys.input_text)

## Declaration

```lua
sys.input_text(text [, press_enter_when_done ])
```

## Parameters

- text
  String. The text to input. Since 2025-06-25, `"\b"` (backspace) is supported.
- press_enter_when_done
  Boolean. Whether to press the Enter key (Send/Search etc.) after input. Default: false.

## Description

> Inputs text into the current foreground app's focused text field.
> This function writes the text to the system clipboard and pastes it using the keyboard shortcut (Cmd+V).
> This call affects the shared clipboard. Back up important clipboard data before calling.
> If the system clipboard is broken (i.e. copy/paste does not work), this function will fail.
> Known conflicting tweak: Background Manager.
> If it does not work for your case, consider [`key.send_text`](/en/docs/handbook/key/key.send_text.md).

## Examples

```lua
sys.input_text("hello") -- Type "hello" at the current cursor
--
sys.input_text("hello", true) -- Type "hello" and press Enter (to trigger send/search in chat or search fields)
```

---

Source: [Block and wait for another task (thread.wait)](https://xxtouch.app/en/docs/handbook/thread/thread.wait.md)
Path: handbook/thread/thread.wait.md

# Block and wait for another task (thread.wait)

## Declaration

```lua
thread.wait(task_id, timeout_seconds)
```

## Parameters

- task_id
  Integer.
- timeout_seconds
  Number. Timeout in seconds. Returns after timeout.

## Description

Block the current thread and wait for another task to finish.

## Example

See [the consolidated examples at the end of this chapter](/en/docs/handbook/thread/samples.md)

---

Source: [! Press with force on screen (:press)](https://xxtouch.app/en/docs/handbook/touch/touchm_press.md)
Path: handbook/touch/touchm_press.md

# ! Press with force on screen (:press)

## Declaration

```lua
te = te:press([ pressure, speed ])
```

## Parameters

- pressure
  Integer, optional. Pressure range 1~10000. Default: 1000.
- speed
  Integer, optional. Apply pressure speed, range 1~100. Default: fastest.

## Returns

- te
  Touch event object itself. You can get a touch event object via [`touch.on`](/en/docs/handbook/touch/touch.on.md).

## Description

- Simulate applying pressure at current position. Only available on devices that support 3D Touch.
- This method may yield; other [threads](/en/docs/handbook/thread/index.md) may run before it returns.

## Example

```lua
touch.on(100, 100):press():off() -- touch at 100,100, apply default pressure, then lift

touch.on(100, 100):press(2000):off() -- same as above but with pressure 2000

touch.on(100, 100):press(2000, 50):off() -- same as above with a slower press speed
```

---

Source: [ui_element Examples](https://xxtouch.app/en/docs/handbook/ui_element/samples.md)
Path: handbook/ui_element/samples.md

# ui_element Examples

> **This module is available in versions after 20260507**

## Find and Click a Button

```lua
local ui_element = require("ui_element")

local ok, info_or_err = ui_element.click({
    title = "Continue",
    role = "button",
})

if not ok then
    sys.toast(info_or_err)
end
```

## Find a Search Field and Enter Text

```lua
local ui_element = require("ui_element")

local search, err = ui_element.find({
    title = "Search",
    role = "text_field",
})

if search then
    ui_element.set_text(search, "XXTouch")
else
    sys.toast(err)
end
```

## Read Text on the Current Page

```lua
local ui_element = require("ui_element")

local list, err = ui_element.list_text_elements({
    max_level = 1,
})

if list then
    for _, item in ipairs(list) do
        if item.text then
            nLog(item.text)
        end
    end
else
    sys.toast(err)
end
```

## Scroll the Current Page

```lua
local ui_element = require("ui_element")

ui_element.scroll("down", {
    point = { x = 200, y = 700 },
})
```

## Set a Switch

```lua
local ui_element = require("ui_element")

ui_element.set_checked({
    title = "Airplane Mode",
    role = "switch",
}, false)
```

## Reuse One Snapshot

```lua
local ui_element = require("ui_element")

local ui, err = ui_element.snapshot({
    max_level = 2,
})

if ui then
    local item = ui:find({ text_contains = "Privacy" })
    if item then
        ui:click(item)
    end
else
    sys.toast(err)
end
```

## Adjust a Slider or Picker

```lua
local ui_element = require("ui_element")

ui_element.increase({
    role = "slider",
    index = 1,
})

ui_element.decrease({
    role = "picker",
    index = 1,
}, {
    steps = 2,
})
```

**Note**: Uses non-chapter APIs [`sys.toast`](/en/docs/handbook/sys/sys.toast.md) and [`nLog`](/en/docs/handbook/develop-helper/nLog.md).

---

Source: [Get Launch Arguments (utils.launch_args)](https://xxtouch.app/en/docs/handbook/utils/utils.launch_args.md)
Path: handbook/utils/utils.launch_args.md

# Get Launch Arguments (utils.launch_args)

## Declaration

```lua
args = utils.launch_args()
```

## Returns

- args
  Table. A table describing the current launch parameters. Inspect with [table.deep_dump](/en/docs/handbook/ext-table/table.deep_dump.md).

## Description

> Get current script launch arguments. Recommended to use with [Activator](https://cydia.saurik.com/package/libactivator/).

## Examples

```lua
sys.alert(table.deep_dump(utils.launch_args()))
```
Note: uses [`sys.alert`](/en/docs/handbook/sys/sys.alert.md), [`table.deep_dump`](/en/docs/handbook/ext-table/table.deep_dump.md)
```lua
-- Current script file path (not all scripts have a path)
sys.alert("Script path: "..tostring(utils.launch_args().path))
```
Note: uses [`sys.alert`](/en/docs/handbook/sys/sys.alert.md), [tostring](https://www.lua.org/manual/5.3/manual.html#pdf-tostring)

---

Source: [Delete a VPN profile (vpnconf.delete)](https://xxtouch.app/en/docs/handbook/vpnconf/vpnconf.delete.md)
Path: handbook/vpnconf/vpnconf.delete.md

# Delete a VPN profile (vpnconf.delete)

## Declaration

```lua
ok = vpnconf.delete(nameOrId)
```

## Parameters

- nameOrId
  String. Display name or VPNID. If multiple profiles share the same name, deletion is not deterministic. Use VPNID for precise deletion.

## Returns

- ok
  Boolean. true on success; false on failure (usually because the specified profile does not exist).

## Description

> VPNID can be obtained with [vpnconf.list](/en/docs/handbook/vpnconf/vpnconf.list.md).

## Example

```lua
local success = vpnconf.delete('DemoVPN')
if success then
    sys.alert('Operation succeeded')
else
    sys.alert('Operation failed. Please verify the target VPN exists.')
end
```
**Note**: Uses [`sys.alert`](/en/docs/handbook/sys/sys.alert.md)

## Delete all VPN profiles example

```lua
-- Delete all VPNs
local vpnlist = vpnconf.list()
if vpnlist then
    for _,v in ipairs(vpnlist) do
        if (vpnconf.delete(v.VPNID)) then
            sys.log('Deleted: '..v.dispName..'('..v.VPNID..')')
        else
            sys.log('Cannot delete: '..v.dispName..'('..v.VPNID..')')
        end
    end
    sys.alert('Done!')
else
    sys.alert('Failed to get list')
end
```
**Note**: Uses [`sys.alert`](/en/docs/handbook/sys/sys.alert.md), [`sys.log`](/en/docs/handbook/sys/sys.log.md)

---

Source: [Get webview frame and level (webview.frame)](https://xxtouch.app/en/docs/handbook/webview/webview.frame.md)
Path: handbook/webview/webview.frame.md

# Get webview frame and level (webview.frame)

## Declaration

```lua
frame = webview.frame([ id ])
```

## Parameters

- id
  Integer. Optional. Current webview id (1 ~ 1000). Default 1.

## Returns

- frame
  Table. The frame and level information of the current webview.

## Description

Get the frame and level information of a webview.

## Example

```lua
local frame = webview.frame(1)
sys.alert(
    "Origin:".."("..frame.x..","..frame.y..")\n"..
    "Size:".."(".."W:"..frame.width..", ".."H:"..frame.height..")\n"..
    "Level:".."("..frame.level..")"
)
```
**Note**: Uses [`sys.alert`](/en/docs/handbook/sys/sys.alert.md)

---

Source: [Dismiss the Currently Displayed Config UI (xui.dismiss)](https://xxtouch.app/en/docs/handbook/xui/xui.dismiss.md)
Path: handbook/xui/xui.dismiss.md

# Dismiss the Currently Displayed Config UI (xui.dismiss)

## Declaration

```lua
xui.dismiss()
```

## Description

> Attempt to let the App dismiss the configuration UI and return to the main screen.
> This function is non-blocking and has no return value. If no configuration UI is currently displayed, it merely foregrounds the App and does nothing else.
> See the config UI standard: [XUI](/XUI/README.md)

## Examples

```lua
xui.dismiss()
```

---

Source: [Post an app notification (app.pop_banner)](https://xxtouch.app/en/docs/handbook/app/app.pop_banner.md)
Path: handbook/app/app.pop_banner.md

# Post an app notification (app.pop_banner)

## Declaration

```lua
app.pop_banner(bid, title, body)
```

## Parameters

- bid
  String. App bundle identifier. You can find it in `XXT App -> More -> App List`.
- title
  String. Notification title.
- body
  String. Notification body.

## Description

- Requires full jailbreak and the dependency "libbulletin" installed via Cydia/Sileo.

## Example

```lua
app.pop_banner('com.tencent.mqq', 'QQ', 'You have a new message')
```

---

Source: [Delete all local photos in Photos app (clear.all_photos)](https://xxtouch.app/en/docs/handbook/clear/clear.all_photos.md)
Path: handbook/clear/clear.all_photos.md

# Delete all local photos in Photos app (clear.all_photos)

## Declaration

```lua
clear.all_photos()
```

## Description

> Delete all local photos from the Photos app; iCloud Photo Stream is not affected.
> This function can take a very long time; force-stopping the script mid-run can be slow (it may require a hard kill).
> **WARNING:** The effect of this function is irreversible.

## Example

```lua
clear.all_photos()
```

---

Source: [Methods on a general-purpose CoreML request](https://xxtouch.app/en/docs/handbook/coreml/coreml_model_request_object_methods.md)
Path: handbook/coreml/coreml_model_request_object_methods.md

# Methods on a general-purpose CoreML request

`coreml_model_request_object` is the inference object returned by `coreml.new_model_request(...)` / `coreml.session(...)`.
It sends prepared input features into the model and returns results organized by output name.

Its responsibilities are intentionally narrow:

- submit inference
- read asynchronous results
- inspect input/output signatures
- inspect the current request configuration

It does not perform tokenization, image preprocessing, or business-level post-processing; those should be composed in Lua.

> **These methods are available in versions released after 20260319**

## Inference methods

### `:predict(inputs[, opts])`

```lua
result, err = request:predict(inputs)
```

or

```lua
submitted, err = request:predict(inputs, {
    async = is_async,
    multi_array_output = "table" or "MLMultiArray",
    uses_cpu_only = cpu_only_for_this_call,
})
```

Runs inference for a single sample.

- `inputs` must be a table keyed by input name
- In synchronous mode, the result table is returned directly
- In asynchronous mode, only `true` is returned; use `:is_done()` and `:results()` later
- `multi_array_output` controls whether `MLMultiArray` outputs stay as native tensor objects or are converted to Lua tables
- `uses_cpu_only` affects only this call and does not change the object's default configuration

### `:run(inputs[, opts])`

`run()` is an alias of `predict()`.

### `:predict_batch(batch_inputs[, opts])`

```lua
batch_result, err = request:predict_batch({
    { input_ids = ids1 },
    { input_ids = ids2 },
}, {
    async = false,
    multi_array_output = "MLMultiArray",
})
```

Runs batch inference. **Requires iOS 12+**.

- `batch_inputs` must be an array; each item is a single-sample input table keyed by input name
- In synchronous mode, returns a batch result array; each element still follows the single-sample output structure
- In asynchronous mode, returns `true`; call `:results()` later to retrieve the batch result
- `opts` uses the same fields as `predict()`

### `:run_batch(batch_inputs[, opts])`

`run_batch()` is an alias of `predict_batch()`.

### `:results([opts])`

```lua
result, err = request:results()
```

or

```lua
result, err = request:results({
    multi_array_output = "table" or "MLMultiArray",
})
```

Reads the result of the most recent asynchronous inference.

- If the last async call came from `predict()`, this returns a single-sample result table
- If the last async call came from `predict_batch()`, this returns a batch result array
- `multi_array_output` defaults to the setting used by the latest inference call
- If the async job is still running, it returns `nil, "not yet"`
- If there is no successful completed result to read, it returns `nil, "unknown"`

### `:is_done()`

```lua
done = request:is_done()
```

Checks whether the most recent asynchronous inference has completed. This only makes sense after `predict(..., { async = true })` or `predict_batch(..., { async = true })`.

## Runtime configuration and metadata

### `:metadata()`

```lua
metadata = request:metadata()
```

Returns the model's built-in metadata.

### `:uses_cpu_only()`

```lua
cpu_only = request:uses_cpu_only()
```

Returns the default CPU-only configuration saved when the request was created.

### `:compute_units()`

```lua
compute_units = request:compute_units()
```

Returns the current `compute_units` string recorded by this request.

- On **iOS 12+**, this returns the lowercased string recorded at creation time
- Common results include `"all"`, `"cpu_only"`, `"cpu"`, `"cpu_and_gpu"`, `"gpu"`, `"cpu_and_neural_engine"`, `"ane"`, and `"neural_engine"`
- If the request was created with `uses_cpu_only = true`, this returns `"cpu_only"`
- On **iOS 11**, it returns `nil`

## Input and output signature methods

### `:input_count()` / `:output_count()`

Return the number of input / output features.

### `:input_features()` / `:output_features()`

Return name-keyed feature description tables.

The current implementation exposes a compact set of fields:

- `type`
- `optional`
- For `multi_array` features only, `shape` and `data_type`

### `:input_info(name_or_index)` / `:output_info(name_or_index)`

Read a single input / output description by name or by **1-based** index.

- The returned fields mostly match `input_features()` / `output_features()`
- An extra `name` field is included
- Numeric indexing follows the same ordering used by `input_names()` / `output_names()`

### `:input_names()` / `:output_names()`

Return stable ordered lists of input / output names.

- Names are sorted lexicographically
- The order of `output_names()` matches the numeric index order in synchronous inference results

### `:class_labels()`

Returns the model-declared class labels. **Requires iOS 14+**.

## Lifecycle and type checks

### `:close()`

Destroys the underlying request state. The object should not be used again after closing.

### `:is_model_request()` / `:is_session()`

Object-level type-check helpers. These are equivalent aliases.

## Notes

- `predict()` / `run()` always return a table
- Results support both numeric indexing and output-name indexing
- `predict_batch()` / `run_batch()` return a batch result array; each item still supports both numeric and output-name access
- In the newer general-purpose request APIs, `MLMultiArray` outputs are kept as native tensor objects by default for further processing
- To inspect values or maintain compatibility with older table-based scripts, pass `multi_array_output = "table"`

Result access examples:

```lua
out[1]
out.text_features
batch_out[1].text_features
```

## Example

```lua
local req = assert(coreml.new_model_request(XXT_HOME_PATH.."/models/demo.mlmodelc"))

local out = assert(req:predict({
    input_ids = ids,
}, {
    multi_array_output = "MLMultiArray",
}))

print(out[1])
print(out.text_features)
print(req:output_names())
```

---

Source: [Get system-root path for a jailbreak-root path (rootfs)](https://xxtouch.app/en/docs/handbook/develop-helper/rootfs.md)
Path: handbook/develop-helper/rootfs.md

# Get system-root path for a jailbreak-root path (rootfs)

## Declaration

```lua
sysRootPath = rootfs(jbPath)
```

## Parameters

- jbPath
  String. A path under the jailbreak root.

## Returns

- sysRootPath
  String. The system-root path corresponding to `jbPath`.

## Description

> On roothide and rootless editions of XXTouch, this converts a jailbreak-root path back to its system-root equivalent (the inverse of `jbroot`).
> On rootful or TrollStore editions, this simply returns the input parameter.
> **Available since version 1.3.8 or later.**

## Example

```lua
nLog(rootfs('/var/containers/Bundle/Application/.jbroot-XXXXXXXXXXXXXXXX/')) -- /
```

---

Source: [Get Front App Orientation (device.front_orien)](https://xxtouch.app/en/docs/handbook/device/device.front_orien.md)
Path: handbook/device/device.front_orien.md

# Get Front App Orientation (device.front_orien)

## Declaration

```lua
orien = device.front_orien()
```

## Returns

- orien
  Integer. Screen orientation of the foreground app:
  `0` Home at bottom (portrait)
  `1` Home at right (landscape)
  `2` Home at left (landscape)
  `3` Home at top (portrait, upside down)
  `4` Failed to retrieve

## Example

```lua
sys.toast('Toast shows with the front app orientation', device.front_orien())
```
**Note**: Uses [`sys.toast`](/en/docs/handbook/sys/sys.toast.md)

---

Source: [Set dialog size (:set_size)](https://xxtouch.app/en/docs/handbook/dialog/dialogm_set_size.md)
Path: handbook/dialog/dialogm_set_size.md

# Set dialog size (:set_size)

## Declaration

```lua
dialog_obj = dialog_obj:set_size(width, height)
```

## Parameters

- width, height
  Integer. Dialog size. If not set elsewhere, defaults to full screen

## Returns

- dialog_obj
  Dialog. Returns the dialog itself

## Description

> Set the dialog's size. If not full screen, it will be centered with a corner radius of 10.
> This method works only for dialogs that use the webview engine.

## Example

```lua
local dlg = dialog()
dlg:set_size(600, 800)
dlg:show()
```

---

Source: [Overwrite data to a file (file.writes)](https://xxtouch.app/en/docs/handbook/file/file.writes.md)
Path: handbook/file/file.writes.md

# Overwrite data to a file (file.writes)

## Declaration

```lua
ok, err = file.writes(path, content)
```

## Parameters

- path
  String. Absolute file path.
- content
  String. Data to write.

## Returns

- ok
  Boolean. true if success, false if failure.
- err
  String. Error message when operation fails.

## Description

> Overwrite data to a file. Creates file if it does not exist. Returns false if directory does not exist.

## Example

```lua
local success, err = file.writes("/var/mobile/1.txt", "Hello")
if success then
    sys.alert("Write success")
else
    sys.alert("Write failed: "..err)
end
```
**Note**: Uses [`sys.alert`](/en/docs/handbook/sys/sys.alert.md)

---

Source: [Set an analog-stick position (:set_stick)](https://xxtouch.app/en/docs/handbook/gamepad/gamepadm_set_stick.md)
Path: handbook/gamepad/gamepadm_set_stick.md

# Set an analog-stick position (:set_stick)

> **This method is available in versions after 20260805**

## Declaration

```lua
success, err = pad:set_stick(stick, x, y)
```

## Parameters

- stick
  String. `"left"` or `"right"`; matching is case-insensitive
- x
  Number. A finite value in `[-1, 1]`; positive moves right and negative moves left
- y
  Number. A finite value in `[-1, 1]`; positive moves up and negative moves down

## Returns

- success
  Boolean. True if the analog-stick position is set; false if the device is disconnected or busy, or if input delivery fails
- err
  String. Error message when the operation fails

## Description

- `0, 0` centers the analog stick
- The analog stick moves directly to `(x, y)` without generating a smooth movement sequence
- Invalid argument types, unknown stick names, non-finite numbers, and out-of-range values raise Lua argument errors

## Example

```lua
local pad = assert(gamepad.connect())

assert(pad:set_stick("left", 0.5, 1))
assert(pad:set_stick("left", 0, 0))
assert(pad:disconnect())
```

---

Source: [Send HEAD request (http.head)](https://xxtouch.app/en/docs/handbook/http/http.head.md)
Path: handbook/http/http.head.md

# Send HEAD request (http.head)

## Declaration

```lua
code, res_headers_json = http.head(URL [, timeout_secs, headers, url_no_escape])
```

## Declaration (named arguments)

**Supported since 2025-06-25; progress options are supported since 2026-04-02**
```lua
code, res_headers_json = http.head{
    url = URL;
    timeout = timeout_secs;
    headers = headers;
    params = query_params;
    progress = progress_callback;
    progress_interval_ms = progress_interval_ms;
}
```

## Parameters

- URL
  String. Request URL. The function escapes the URL by default; see "url_no_escape" if you don't want this.
- timeout_secs
  Number, optional. Timeout in seconds. Default 10.
- headers
  Table, optional. Request headers in the form `{ field1 = value1, ... }`. Default `{}`.
- query_params
  Table, optional. Query string parameters in the form `{ field1 = value1, ... }`. Default `{}`.
- progress_callback
  Function, optional. Supported since 2026-04-02. Called when request progress changes. The first argument is the current progress info.
- progress_interval_ms
  Integer, optional. Supported since 2026-04-02. Progress callback interval in milliseconds.
- url_no_escape
  Boolean, optional. true = do not escape URL. Default false.
  For custom escaping, see the [`lcurl` module](/en/docs/handbook/open-source/lcurl.md) [easy:escape](https://lua-curl.github.io/lcurl/modules/lcurl.html#easy:escape) and [easy:unescape](https://lua-curl.github.io/lcurl/modules/lcurl.html#easy:unescape).

## Returns

- code
  Integer. HTTP status code. -1 on timeout.
- res_headers_json
  String or nil. Response headers in JSON. nil on timeout.

## Description

> Use HTTP/1.1 HEAD method to fetch response headers.
> HEAD typically returns the same headers as GET but without body.
> This function may yield; other [threads](/en/docs/handbook/thread/index.md) may run before it returns.

The `info` table passed to the progress callback has this structure:

```lua
{
    count_of_bytes_sent = bytes_sent;
    count_of_bytes_expected_to_send = bytes_expected_to_send;
    count_of_bytes_received = bytes_received;
    count_of_bytes_expected_to_receive = bytes_expected_to_receive;
}
```

## Example

```lua
local c, h = http.head("https://www.xxtouch.app/测试文本.txt")
if c==200 then
    sys.alert(h)
end
```
**Note**: Uses [`sys.alert`](/en/docs/handbook/sys/sys.alert.md)

---

Source: [Create an image from a file (image.load_file)](https://xxtouch.app/en/docs/handbook/image/image.load_file.md)
Path: handbook/image/image.load_file.md

# Create an image from a file (image.load_file)

## Declaration

```lua
img = image.load_file(path)
```

## Parameters

- path
  String. Absolute path to an image file

## Returns

- img
  Image object or nil. Returns newly created image object, or nil if file does not exist

## Description

> Create an image object from file
> This call creates a new image object. For efficient frequent usage, please pair with [image:destroy](/en/docs/handbook/image/imagem_destroy.md)

## Example

[`Save the file image to Photos`](/en/docs/handbook/image/imagem_save_to_album.md)

---

Source: [Input Text (key.input_text)](https://xxtouch.app/en/docs/handbook/key/key.input_text.md)
Path: handbook/key/key.input_text.md

# Input Text (key.input_text)

> **This function is available in versions after 20260816**

## Declaration

```lua
success, error = key.input_text(text [, press_enter_when_done ])
```

## Parameters

- text
  String. The UTF-8 text to input. It may be empty. Each `"\b"` performs a Backspace action.
- press_enter_when_done
  Boolean. Whether to press Enter after entering the text. Default: false.

## Return Values

- success
  Boolean. Returns `true` when the simulated input operation is sent, or `false` on failure.
- error
  String. The error reason when the operation fails.

## Description

> Enters text into the focused field of the foreground app by simulating the way an input method commits selected text.
>
> This function does not read or modify the shared system pasteboard.
>
> **This function cannot enter text into password fields. Use [`sys.input_text`](/en/docs/handbook/sys/sys.input_text.md) for password fields.**
>
> A `true` return value only means that the simulated input operation was sent; it does not guarantee that the target field accepted the text.

## Examples

```lua
local ok, err = key.input_text("Hello, XXTouch 🙂")
assert(ok, err)
--
local ok, err = key.input_text("hello!\b", true)
assert(ok, err)
```

---

Source: [Examples and supported key codes](https://xxtouch.app/en/docs/handbook/key/samples.md)
Path: handbook/key/samples.md

# Examples and supported key codes

## Simulate pressing the HOME key

```lua
key.press("HOMEBUTTON")
```

## Simulate long-pressing the HOME key

```lua
key.down("HOMEBUTTON") -- press the HOME key
sys.msleep(1000) -- wait 1 second
key.up("HOMEBUTTON") -- release the HOME key
```

## Simulate double-clicking the HOME key

```lua
key.press("HOMEBUTTON")
key.press("HOMEBUTTON")
```

## Simulate pressing the Lock (power) key

```lua
key.press("LOCK")
```

## Simulate pressing the Return key

```lua
key.press("RETURN")
```

## Other simulations

```lua
-- The example below simulates the shortcut [Command + V] to paste clipboard text
-- (it's Command on iOS, not Control on Windows)
key.down("LEFTCOMMAND") -- press Command
sys.msleep(30) -- wait 30 ms
key.press("V") -- press V
sys.msleep(30) -- wait 30 ms
key.up("LEFTCOMMAND") -- release Command
--
-- The example below simulates Command + [ to go back
key.down("LEFTCOMMAND") -- press Command
sys.msleep(30) -- wait 30 ms
key.press("[") -- press [
sys.msleep(30) -- wait 30 ms
key.up("LEFTCOMMAND") -- release Command
--
-- The example below simulates [Command + A] select-all, then Backspace to delete
key.down('LEFTCOMMAND')
sys.msleep(30) -- wait 30 ms
key.press('A') -- press A
sys.msleep(30) -- wait 30 ms
key.up('LEFTCOMMAND')
sys.msleep(100) -- wait 100 ms
key.press('BACKSPACE') -- press Backspace
--
--
key.press("VOLUMEUP") -- press Volume +
key.press("VOLUMEDOWN") -- press Volume -
--
key.down("VOLUMEUP") -- press and hold Volume +
sys.msleep(1000) -- wait 1 second
key.up("VOLUMEUP") -- release Volume +
--
key.down("LOCK") -- press and hold Lock (power)
sys.msleep(3000) -- wait 3 seconds
key.up("LOCK") -- release Lock (power)
--
key.press("SHOW_HIDE_KEYBOARD") -- press [Show/Hide Keyboard] to hide the on-screen keyboard
--
key.press("SHOW_HIDE_KEYBOARD") -- press [Show/Hide Keyboard] again to show the on-screen keyboard
--
-- The example below simulates [Lock + HOME] to take a screenshot to the photo album
key.down("LOCK") -- press Lock (power)
sys.msleep(100) -- wait 100 ms
key.press("HOMEBUTTON") -- press HOME
sys.msleep(100) -- wait 100 ms
key.up("LOCK") -- release Lock (power)
--
-- iOS 7/8 input method switch shortcut
key.down("LEFTCOMMAND")
sys.msleep(50)
key.press(" ")
sys.msleep(50)
key.up("LEFTCOMMAND")
--
-- iOS 9 input method switch shortcut
key.down("LEFTCONTROL")
sys.msleep(50)
key.press("SPACE")
sys.msleep(50)
key.up("LEFTCONTROL")
```
**Note**: The above code uses a function not in this chapter: [`sys.msleep`](/en/docs/handbook/sys/sys.msleep.md)

## Supported key codes

```lua
-- Letters:
"A" "B" "C" "D" "E" "F" "G" "H" "I" "J" "K" "L" "M" "N" "O" "P" "Q" "R" "S" "T" "U" "V" "W" "X" "Y" "Z"
--
-- Digits:
"1" "2" "3" "4" "5" "6" "7" "8" "9" "0"
--
-- Function keys:
"F1" "F2" "F3" "F4" "F5" "F6" "F7" "F8" "F9" "F10" "F11" "F12"
--
-- Other keys:
"RETURN"        --< Return
"ESCAPE"        --< Esc
"BACKSPACE"     --< Backspace
"TAB"           --< Tab
"SPACE"         --< Space
"HYPHEN"        --< "-" or "_"
"EQUAL"         --< "=" or "+"
"BRACKETOPEN"   --< "[" or "{"
"BRACKETCLOSE"  --< "]" or "}"
"BACKSLASH"     --< "\\" or "|"
"SEMICOLON"     --< ";" or ":"
"QUOTATION"     --< Single-quote or double-quote
"ACCENT"        --< "`" or "~"
"COMMA"         --< "," or "<"
"DOT"           --< "." or ">"
"SLASH"         --< "/" or "?"
"CAPSLOCK"      --< Caps Lock
"PAUSE"
"INSERT"
"HOME"          --< Not exactly the HOME key on iOS devices
"PAGEUP"
"DELETE"
"END"
"PAGEDOWN"
"RIGHTARROW"    --< Right arrow
"LEFTARROW"     --< Left arrow
"DOWNARROW"     --< Down arrow
"UPARROW"       --< Up arrow
"LEFTCONTROL"   --< Left Ctrl
"LEFTSHIFT"     --< Left Shift
"LEFTALT"       --< Left Alt
"LEFTCOMMAND"   --< Left Command
"RIGHTCONTROL"  --< Right Ctrl
"RIGHTSHIFT"    --< Right Shift
"RIGHTALT"      --< Right Alt
"RIGHTCOMMAND"  --< Right Command
"LOCK"          --< Lock (power)
"HOMEBUTTON"    --< This is the HOME key on iOS devices
"FORWARD"       --< Media next
"REWIND"        --< Media previous
"FORWARD2"      --< Media next (alternate)
"REWIND2"       --< Media previous (alternate)
"EJECT"
"PLAYPAUSE"     --< Media pause
"MUTE"          --< Mute
"VOLUMEUP"      --< Volume +
"VOLUMEDOWN"    --< Volume -
"SPOTLIGHT"     --< Spotlight
"BRIGHTUP"      --< Brightness +
"BRIGHTDOWN"    --< Brightness -
"SHOW_HIDE_KEYBOARD" --< Show/Hide keyboard
```

---

Source: [! Click a hardware mouse button (:click)](https://xxtouch.app/en/docs/handbook/mouse/mousem_click.md)
Path: handbook/mouse/mousem_click.md

# ! Click a hardware mouse button (:click)

> **This method is available in versions after 20260805**


## Declaration

```lua
success, error_message = mouse_obj:click(button[, press_delay_ms])
```


## Parameters

- button
  Integer or string. Pass a value from `1` through `32` or a predefined button name. See the [`:down` button description](mousem_down.md).
- press_delay_ms
  Finite non-negative number, optional. How long to hold the button down, in milliseconds. Default: 60.


## Returns

- success
  Boolean. `true` if the click succeeds; otherwise `false`.
- error_message
  String. The reason the click failed.


## Description

> Press and release the specified button. Only the target button is changed; other buttons that are already held down are not released.
> If the target button is already held down, the call fails to avoid disrupting a drag operation.
> **This method yields the current Lua execution thread while holding the button. During that interval, other operations on the same mouse object return `false, "hardware mouse is busy"`; different mouse objects can still be operated independently.**


## Example

```lua
local m = assert(mouse.connect())
assert(m:click("right"))
assert(m:click(13, 100))
assert(m:click(32))
assert(m:disconnect())
```

---

Source: [LuaFileSystem](https://xxtouch.app/en/docs/handbook/open-source/luafilesystem.md)
Path: handbook/open-source/luafilesystem.md

# LuaFileSystem

[LuaFileSystem manual](https://lunarmodules.github.io/luafilesystem/manual.html#reference)

---

## Example: iterate all filenames in a path

```lua
local lfs = require("lfs")
for filename in lfs.dir("/var/mobile") do
    if (filename ~= ".." and filename ~= ".") then
        print(filename)
    end
end
sys.alert(print.out())
```
**Note**: Uses [`sys.alert`](/en/docs/handbook/sys/sys.alert.md)

## Example: get file/dir attributes

```lua
local lfs = require("lfs")
--
local attr = lfs.attributes("/var/mobile")
--
print("type", attr.mode)
print("last access", os.date("%Y-%m-%d %H:%M:%S", attr.access))
print("last modification", os.date("%Y-%m-%d %H:%M:%S", attr.modification))
print("last status change", os.date("%Y-%m-%d %H:%M:%S", attr.change))
--
sys.alert(print.out())
```
**Note**: Uses [`sys.alert`](/en/docs/handbook/sys/sys.alert.md)

## Example: get and change current directory

```lua
local lfs = require 'lfs'
--
sys.alert(lfs.currentdir()) -- prints "/"
--
lfs.chdir('/var/mobile/Media/1ferver/lua/scripts')
--
sys.alert(lfs.currentdir()) -- prints "/var/mobile/Media/1ferver/lua/scripts"
```
**Note**: Uses [`sys.alert`](/en/docs/handbook/sys/sys.alert.md)

---

Source: [Convert plist data format (plist.data_convert)](https://xxtouch.app/en/docs/handbook/plist/plist.data_convert.md)
Path: handbook/plist/plist.data_convert.md

# Convert plist data format (plist.data_convert)

## Declaration

```lua
converted = plist.data_convert(plistData [, format])
```

## Parameters

- plistData
  String. The plist data to convert.
- format
  String, optional. One of "binary", "XML", or "openstep". Default: "XML".

## Returns

- converted
  String or nil. Converted plist data on success; nil on failure.

## Description

> Pure plist format conversion. It does not involve Lua serialization/deserialization and guarantees data integrity.

## Example

```lua
local xplist = plist.data_convert(file.reads('/var/mobile/Library/UserNotifications/Library.plist'), "xml")
sys.alert(xplist) -- XML formatted plist data
```
**Note**: Uses [`file.reads`](/en/docs/handbook/file/file.reads.md), [`sys.alert`](/en/docs/handbook/sys/sys.alert.md)

---

Source: [Pop all values from a process queue (proc_queue_clear)](https://xxtouch.app/en/docs/handbook/proc/proc_queue_clear.md)
Path: handbook/proc/proc_queue_clear.md

# Pop all values from a process queue (proc_queue_clear)

## Declaration

```lua
values = proc_queue_clear(key)
```

## Parameters

- key
  String.

## Returns

- values
  Array (list). Returns a list containing all popped values. If the queue does not exist or is empty, returns an empty list.

## Description

- All process queues whose names start with "xxtouch." or "1ferver." are reserved.
- Pop all values from the specified process queue and clear it.

## Example

```lua
local billnos = proc_queue_clear("billnos")
if #billnos ~= 0 then
    for i, billno in ipairs(billnos) do
        print(i, billno)
    end
else
    print("no bill")
end
```

---

Source: [Get Color at Point (screen.get_color)](https://xxtouch.app/en/docs/handbook/screen/screen.get_color.md)
Path: handbook/screen/screen.get_color.md

# Get Color at Point (screen.get_color)

## Declaration

```lua
color = screen.get_color(x, y)
```

## Parameters

- x, y
  Integer. Target coordinates.

## Returns

- color
  Integer. RGB value of the point.

## Description

> Get the color at a screen coordinate.
> Coordinate parameters follow the coordinate system initialized via [`screen.init`](/en/docs/handbook/screen/screen.init.md).

## Example

```lua
local c = screen.get_color(512, 133)
if c==0xffffff then
    sys.alert("Point 512,133 is pure white")
end
```
**Note**: Uses [`sys.alert`](/en/docs/handbook/sys/sys.alert.md)

---

Source: [URL Scheme Usages](https://xxtouch.app/en/docs/handbook/supplement/url-scheme.md)
Path: handbook/supplement/url-scheme.md

# URL Scheme Usages

See details: [app.open_url](/en/docs/handbook/app/app.open_url.md)

| URL Scheme | Jumps To |
|----|----|
|prefs:root=WIFI|Settings - Wi-Fi|
|prefs:root=Bluetooth|Settings - Bluetooth|
|prefs:root=INTERNET_TETHERING|Settings - Personal Hotspot|
|prefs:root=Wallpaper|Settings - Wallpaper & Brightness|
|prefs:root=Sounds|Settings - Sounds|
|prefs:root=Sounds&path=Ringtone|Settings - Sounds - Ringtone|
|prefs:root=Photos|Settings - Photos & Camera|
|prefs:root=STORE|Settings - iTunes Store & App Store|
|prefs:root=SAFARI|Settings - Safari|
|prefs:root=SAFARI&path=CLEAR_HISTORY_AND_DATA|Settings - Safari - Clear History and Website Data|
|prefs:root=MUSIC|Settings - Music|
|prefs:root=MUSIC&path=EQ|Settings - Music - EQ|
|prefs:root=VIDEO|Settings - Videos|
|prefs:root=NOTES|Settings - Notes|
|prefs:root=Phone|Settings - Phone|
|prefs:root=CASTLE|Settings - iCloud|
|prefs:root=CASTLE&path=STORAGE_AND_BACKUP|Settings - iCloud - Storage & Backup|
|prefs:root=NOTIFICATIONS_ID|Settings - Notification Center|
|prefs:root=ACCOUNT_SETTINGS|Settings - Mail, Contacts, Calendars|
|prefs:root=LOCATION_SERVICES|Settings - Location Services|
|prefs:root=MESSAGES|Settings - Messages|
|prefs:root=GAMECENTER|Settings - Game Center|
|prefs:root=General|Settings - General|
|prefs:root=General&path=About|Settings - General - About|
|prefs:root=General&path=SOFTWARE_UPDATE_LINK|Settings - General - Software Update|
|prefs:root=General&path=ACCESSIBILITY|Settings - General - Accessibility|
|prefs:root=General&path=ACCESSIBILITY/REDUCE_MOTION|Settings - General - Accessibility - Reduce Motion|
|prefs:root=General&path=ACCESSIBILITY/ENHANCE_BACKGROUND_CONTRAST|Settings - General - Accessibility - Increase Contrast|
|prefs:root=General&path=AUTO_CONTENT_DOWNLOAD|Settings - General - Background App Refresh|
|prefs:root=General&path=USAGE|Settings - General - Usage|
|prefs:root=General&path=AUTOLOCK|Settings - General - Auto-Lock|
|prefs:root=General&path=DATE_AND_TIME|Settings - General - Date & Time|
|prefs:root=General&path=Keyboard|Settings - General - Keyboard|
|prefs:root=General&path=INTERNATIONAL|Settings - General - Language & Region|
|prefs:root=General&path=VPN|Settings - General - VPN|
|prefs:root=General&path=Bluetooth|Settings - General - Bluetooth|
|prefs:root=General&path=Network|Settings - General - Network|
|prefs:root=General&path=Network/VPN|Settings - General - Network - VPN|
|prefs:root=General&path=ManagedConfigurationList|Settings - General - Profiles|
|prefs:root=General&path=Reset|Settings - General - Reset|

[More Settings-related URLs](https://github.com/FifiTheBulldog/ios-settings-urls/blob/master/settings-urls.md)

---

Source: [Millisecond Sleep (sys.msleep)](https://xxtouch.app/en/docs/handbook/sys/sys.msleep.md)
Path: handbook/sys/sys.msleep.md

# Millisecond Sleep (sys.msleep)

## Declaration

```lua
sys.msleep(milliseconds)
```

## Parameters

- milliseconds
  Number. Time to wait in milliseconds.

## Description

> Blocks the current thread for a while.
> This method may yield; other [threads](/en/docs/handbook/thread/index.md) may run before it returns.

## Examples

```lua
sys.msleep(1000) -- wait 1 second
```

---

Source: [Register an event listener (thread.register_event)](https://xxtouch.app/en/docs/handbook/thread/thread.register_event.md)
Path: handbook/thread/thread.register_event.md

# Register an event listener (thread.register_event)

## Declaration

```lua
event_id = thread.register_event(event_name, callback [, on_error ])
```

## Parameters

- event_name
  String. The event name.
- callback
  Function. Callback to invoke when the event is triggered.
- on_error
  Function. Optional error callback. If the callback throws, this will be invoked and no error is rethrown.

## Returns

- event_id
  Integer.

## Description

Register a listener. When the named event in the [process queue dictionary](/en/docs/handbook/proc/proc_queue_push.md) has a value, the value is popped and passed to the callback.

## Example

See [the consolidated examples at the end of this chapter](/en/docs/handbook/thread/samples.md)

---

Source: [Lift finger from screen (:off)](https://xxtouch.app/en/docs/handbook/touch/touchm_off.md)
Path: handbook/touch/touchm_off.md

# Lift finger from screen (:off)

## Declaration

```lua
te:off([ x, y ])
```

## Parameters

- x, y
  Integer, optional. Coordinates where the finger leaves the screen in the current rotation coordinate system. Default: current touch event coordinates recorded by te.

## Returns

- te
  Touch event object itself. You can get a touch event object via [`touch.on`](/en/docs/handbook/touch/touch.on.md).

## Description

> Simulate lifting the finger from the current or specified position. After the call, the touch event object and its occupied finger id are released.
> Coordinate parameters follow the coordinate system initialized via [`screen.init`](/en/docs/handbook/screen/screen.init.md).
> You can also call it in the following forms (finger ID must be 1 ~ 29):
```lua
touch.off(finger_id)
touch.off(finger_id, x, y)
```

## Example

```lua
touch.on(100, 100):off() -- touch at 100,100 then lift at current position

touch.on(100, 100):off(105, 95) -- touch at 100,100 then lift at 105,95

-- Another usage
touch.on(1, 100, 100) -- finger #1 touches at 100,100
for i=1, 100 do       -- move finger #1 step by step to 100,200
    touch.move(1, 100, 100 + i)
end
touch.off(1)          -- lift finger #1
```

---

Source: [Check If Launched via App (utils.is_launch_via_app)](https://xxtouch.app/en/docs/handbook/utils/utils.is_launch_via_app.md)
Path: handbook/utils/utils.is_launch_via_app.md

# Check If Launched via App (utils.is_launch_via_app)

## Declaration

```lua
via_app = utils.is_launch_via_app()
```

## Returns

- via_app
  Boolean. true if launched from the App's start button; otherwise false.

## Description

> Determine whether the current script is launched from within the App.

## Examples

See the usage in [`dialog:load`](/en/docs/handbook/dialog/dialogm_load.md).

---

Source: [Connect using the currently selected VPN (vpnconf.connect)](https://xxtouch.app/en/docs/handbook/vpnconf/vpnconf.connect.md)
Path: handbook/vpnconf/vpnconf.connect.md

# Connect using the currently selected VPN (vpnconf.connect)

## Declaration

```lua
ok = vpnconf.connect()
```

## Returns

- ok
  Boolean. true if the operation started successfully (not necessarily connected yet); false if the operation failed, usually because no profile is selected.

## Example

```lua
local success = vpnconf.connect()
if success then
    sys.alert('Operation succeeded, connecting...')
else
    sys.alert('No VPN selected. After creating a VPN, call vpnconf.select to select it.')
end
```

---

Source: [Destroy a webview (webview.destroy)](https://xxtouch.app/en/docs/handbook/webview/webview.destroy.md)
Path: handbook/webview/webview.destroy.md

# Destroy a webview (webview.destroy)

## Declaration

```lua
webview.destroy([ id ])
```

## Parameters

- id
  Integer. Optional. Current webview id (1 ~ 1000). Default 1.

## Description

- Destroy a webview.
- When a script stops, all webviews shown during its execution will be destroyed automatically.

## Example

See [the consolidated examples at the end of this chapter](/en/docs/handbook/webview/samples.md)

---

Source: [Validate Config UI Settings (xui.setup)](https://xxtouch.app/en/docs/handbook/xui/xui.setup.md)
Path: handbook/xui/xui.setup.md

# Validate Config UI Settings (xui.setup)

## Declaration

```lua
xui.setup(filename)
```

## Parameters

- filename
  String. The .xui file name within the current script bundle to validate. Must be a .xui file inside the current script bundle only.

## Description

> If the config UI has never been configured, this function generates default settings for it; it also validates and corrects the types of stored settings according to the controls declared in the config UI.
> See the config UI standard: [XUI](/XUI/README.md)

## Examples

```lua
xui.setup('interface.xui')
```

---

Source: [Run an app (app.run)](https://xxtouch.app/en/docs/handbook/app/app.run.md)
Path: handbook/app/app.run.md

# Run an app (app.run)

## Declaration

```lua
status = app.run(bid)
```

## Parameters

- bid
  String. App bundle identifier. You can find it in `XXT App -> More -> App List`.

## Returns

- status
  Integer. 0 on success, non-zero on failure.

## Description

- If this function does not work well in your script, try `runApp` instead.

## Example

```lua
-- Open built-in Weather app, then quit
local r = app.run("com.apple.weather") -- bundle id can be found in `XXT App -> More -> App List`
sys.msleep(10 * 1000) -- wait 10 seconds
if r == 0 then
    app.close("com.apple.weather") -- terminate
else
    sys.alert("Launch failed", 3)
end
```
Note: uses non-chapter APIs [`sys.msleep`](/en/docs/handbook/sys/sys.msleep.md) and [`sys.alert`](/en/docs/handbook/sys/sys.alert.md).

---

Source: [Clear an app's saved data (clear.app_data)](https://xxtouch.app/en/docs/handbook/clear/clear.app_data.md)
Path: handbook/clear/clear.app_data.md

# Clear an app's saved data (clear.app_data)

## Declaration

```lua
ok = clear.app_data(bundleId)
```

## Parameters

- bundleId
  String. App bundle identifier. You can find it under "`XXT App -> More -> App List`".

## Returns

- ok
  Boolean. true on success; false otherwise.

## Description

> Clear the app's saved data; all threads are blocked throughout the operation.
> This function may take a very long time; force-stopping the script mid-run can be slow (it may require a hard kill).
> **WARNING:** The effect of this function is irreversible.

## Example

```lua
clear.app_data("com.tencent.xin")
```

---

Source: [Get elapsed milliseconds since script start (get_elapsed_ms)](https://xxtouch.app/en/docs/handbook/develop-helper/get_elapsed_ms.md)
Path: handbook/develop-helper/get_elapsed_ms.md

# Get elapsed milliseconds since script start (get_elapsed_ms)

## Declaration

```lua
ms = get_elapsed_ms()
```

## Returns

- ms
  Number. Elapsed runtime of the script in milliseconds.

## Description

> Returns the elapsed milliseconds for the current script. Paused time is not counted.
> **Available in versions after 2025-05-11.**

## Example

```lua
local tm = get_elapsed_ms()
sys.msleep(1)
tm = get_elapsed_ms() - tm
nLog('sys.msleep(1) took '..tm..' ms')
```

---

Source: [Lock screen rotation (device.lock_orien)](https://xxtouch.app/en/docs/handbook/device/device.lock_orien.md)
Path: handbook/device/device.lock_orien.md

# Lock screen rotation (device.lock_orien)

## Declaration

```lua
device.lock_orien()
```

## Example

```lua
device.lock_orien()
```

---

Source: [Set dialog position and size (:set_frame)](https://xxtouch.app/en/docs/handbook/dialog/dialogm_set_frame.md)
Path: handbook/dialog/dialogm_set_frame.md

# Set dialog position and size (:set_frame)

## Declaration

```lua
dialog_obj = dialog_obj:set_frame(x, y, width, height)
```

## Parameters

- x, y
  Integer. Top-left position of the dialog
- width, height
  Integer. Dialog size. If not set elsewhere, defaults to full screen

## Returns

- dialog_obj
  Dialog. Returns the dialog itself

## Description

> Set the dialog's position and size with sharp corners (no rounded corners).
> This method works only for dialogs that use the webview engine.

## Example

```lua
local dlg = dialog()
dlg:set_frame(0, 0, 600, 800)
dlg:show()
```

---

Source: [Append data to a file (file.appends)](https://xxtouch.app/en/docs/handbook/file/file.appends.md)
Path: handbook/file/file.appends.md

# Append data to a file (file.appends)

## Declaration

```lua
ok, err = file.appends(path, content)
```

## Parameters

- path
  String. Absolute file path.
- content
  String. Data to append.

## Returns

- ok
  Boolean. true if success, false if failure.
- err
  String. Error message when operation fails.

## Description

> Append data to the end of a file. Creates file if it does not exist. Returns false if directory does not exist.

## Example

```lua
local success, err = file.appends("/var/mobile/1.txt", " World")
if success then
    sys.alert("Write success")
else
    sys.alert("Write failed: "..err)
end
```
**Note**: Uses [`sys.alert`](/en/docs/handbook/sys/sys.alert.md)

---

Source: [Set the directional-pad state (:set_dpad)](https://xxtouch.app/en/docs/handbook/gamepad/gamepadm_set_dpad.md)
Path: handbook/gamepad/gamepadm_set_dpad.md

# Set the directional-pad state (:set_dpad)

> **This method is available in versions after 20260805**

## Declaration

```lua
success, err = pad:set_dpad(x, y)
```

## Parameters

- x
  Integer. Must be `-1`, `0`, or `1`; `1` means right and `-1` means left
- y
  Integer. Must be `-1`, `0`, or `1`; `1` means up and `-1` means down

## Returns

- success
  Boolean. True if the directional-pad state is set; false if the device is disconnected or busy, or if input delivery fails
- err
  String. Error message when the operation fails

## Description

- Nonzero x and y values select a diagonal direction
- `0, 0` releases the directional pad
- Invalid argument types and out-of-range values raise Lua argument errors

## Example

```lua
local pad = assert(gamepad.connect())

assert(pad:set_dpad(1, 0))   -- right
assert(pad:set_dpad(-1, 1))  -- up-left
assert(pad:set_dpad(0, 0))   -- release
assert(pad:disconnect())
```

---

Source: [Send DELETE request (http.delete)](https://xxtouch.app/en/docs/handbook/http/http.delete.md)
Path: handbook/http/http.delete.md

# Send DELETE request (http.delete)

## Declaration

```lua
code, res_headers_json, body = http.delete(URL [, timeout_secs, headers, data, url_no_escape])
```

## Declaration (named arguments)

**Supported since 2025-06-25; progress options are supported since 2026-04-02**
```lua
code, res_headers_json, body = http.delete{
    url = URL;
    timeout = timeout_secs;
    headers = headers;
    params = query_params;

    -- The following body options are mutually exclusive, priority: multipart > data > json > upload_file
    multipart = multipart_form;
    data = body_data;
    json = body_json;
    upload_file = upload_file_path;

    download_file = save_response_body_file_path;
    progress = progress_callback;
    progress_interval_ms = progress_interval_ms;
}
```

## Parameters

- URL
  String. Request URL. The function escapes the URL by default; see "url_no_escape" if you don't want this.
- timeout_secs
  Number, optional. Timeout in seconds. Default 10.
- headers
  Table, optional. Request headers in the form `{ field1 = value1, ... }`. Default `{}`.
- query_params
  Table, optional. Query string parameters in the form `{ field1 = value1, ... }`. Default `{}`.
- body_data
  String or Table, optional. Request body.
  Since 2025-06-25, if a table is provided, it is encoded as application/x-www-form-urlencoded.
- multipart_form
  Table, optional. Multipart form data to send.
- body_json
  Table, optional. Body encoded as application/json.
- upload_file_path
  String, optional. Send file content directly as body.
- save_response_body_file_path
  String, optional. If provided, the returned body is the saved file path on success.
- progress_callback
  Function, optional. Supported since 2026-04-02. Called when upload or download progress changes. The first argument is the current progress info.
- progress_interval_ms
  Integer, optional. Supported since 2026-04-02. Progress callback interval in milliseconds.
- url_no_escape
  Boolean, optional. true = do not escape URL. Default false.
  For custom escaping, see the [`lcurl` module](/en/docs/handbook/open-source/lcurl.md) [easy:escape](https://lua-curl.github.io/lcurl/modules/lcurl.html#easy:escape) and [easy:unescape](https://lua-curl.github.io/lcurl/modules/lcurl.html#easy:unescape).

## Returns

- code
  Integer. HTTP status code. -1 on timeout.
- res_headers_json
  String or nil. Response headers in JSON. nil on timeout.
- body
  String or nil. Response body. If saved to file, this is the file path. nil on timeout.

## Description

> Use HTTP/1.1 DELETE method to delete a resource. This endpoint often requires authentication.
> This function may yield; other [threads](/en/docs/handbook/thread/index.md) may run before it returns.

The `info` table passed to the progress callback has this structure:

```lua
{
    count_of_bytes_sent = bytes_sent;
    count_of_bytes_expected_to_send = bytes_expected_to_send;
    count_of_bytes_received = bytes_received;
    count_of_bytes_expected_to_receive = bytes_expected_to_receive;
}
```

## Example

```lua
local code, res_headers, body = http.delete("https://httpbin.org/delete?hello=world&你好=世界", 15, {
    ["User-Agent"] = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0)",
    ["Cookie"] = "a=1; b=2; c=3";
}, "data to send")
if code == 200 then
    sys.alert(body)
end
```
**Note**: Uses [`sys.alert`](/en/docs/handbook/sys/sys.alert.md)

## Example (named arguments)

```lua
local code, res_headers, body = http.delete{
    url = "https://httpbin.org/delete";
    timeout = 15;
    headers = {
        ["User-Agent"] = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0)";
        ["Cookie"] = "a=1; b=2; c=3";
    };
    params = {
        ["hello"] = "world";
        ["你好"] = "世界";
    };
    data = "data to send";
}
if code == 200 then
    sys.alert(body)
end
```
**Note**: Uses [`sys.alert`](/en/docs/handbook/sys/sys.alert.md)

---

Source: [Create an image from data (image.load_data)](https://xxtouch.app/en/docs/handbook/image/image.load_data.md)
Path: handbook/image/image.load_data.md

# Create an image from data (image.load_data)

## Declaration

```lua
img = image.load_data(data)
```

## Parameters

- data
  String. Image data in png or jpeg format

## Returns

- img
  Image object or nil. Returns newly created image object, or nil if data is not a valid image

## Description

> Create an image object from raw data
> This call creates a new image object. For efficient frequent usage, please pair with [image:destroy](/en/docs/handbook/image/imagem_destroy.md)

## Example

[`Download an image from the web and save to Photos`](/en/docs/handbook/image/imagem_save_to_album.md)

---

Source: [! Create an independent hardware keyboard (key.connect_keyboard)](https://xxtouch.app/en/docs/handbook/key/key.connect_keyboard.md)
Path: handbook/key/key.connect_keyboard.md

# ! Create an independent hardware keyboard (key.connect_keyboard)

> **This function is available in versions after 20260805**

## Declaration

```lua
keyboard, err = key.connect_keyboard([properties])
```

## Parameters

- properties
  Table. Optional. Sets the following commonly used device properties; the values shown are used by default when omitted:

```lua
{
    VendorID = 0x5858,
    ProductID = 0x0001,
    Product = "XXTouch Keyboard",
    Manufacturer = "XXTouch",
    Transport = "USB",
}
```

You may also set `VersionNumber`, `SerialNumber`, and `LocationID`. Other properties are not guaranteed to take effect.

## Returns

- keyboard
  Hardware keyboard object. Returns `nil` if creation fails.
- err
  String. Error message returned when creation fails.

On failure, the two return values are `nil, error`.

## Description

> Creates an independent hardware keyboard object. Each object has its own key state and connection lifecycle.
> Waiting for the connection may yield; other [threads](/en/docs/handbook/thread/index.md) may run before the function returns.

- `Transport` only affects how iOS or the target app identifies the keyboard. Setting it to `"Bluetooth"` or `"BluetoothLowEnergy"` does not create a Bluetooth connection, advertise or pair the device, or make it appear in another device's Bluetooth list
- At most six non-modifier keys can be held at once; modifier keys do not count toward this limit. Release some keys before adding more
- The target app may be unable to distinguish which hardware keyboard object produced the input
- This function creates only an independent object and does not change the existing `key.*` APIs. Use [`key.connect_global_keyboard`](key.connect_global_keyboard.md) for that behavior
- Failed input is not retried through another input method

## Example

```lua
local keyboard, err = key.connect_keyboard({
    Product = "XXTouch Keyboard",
})
assert(keyboard, err)

assert(keyboard:press("a"))
assert(keyboard:down("LEFTSHIFT"))
assert(keyboard:press("b"))
assert(keyboard:up("LEFTSHIFT"))
assert(keyboard:send_text("Hello"))

keyboard:disconnect()
```

---

Source: [Scroll the hardware mouse wheel (:scroll)](https://xxtouch.app/en/docs/handbook/mouse/mousem_scroll.md)
Path: handbook/mouse/mousem_scroll.md

# Scroll the hardware mouse wheel (:scroll)

> **This method is available in versions after 20260805**


## Declaration

```lua
success, error_message = mouse_obj:scroll(delta_x, delta_y)
```


## Parameters

- delta_x
  Integer. Scroll steps in the range `[-127, 127]`; positive values scroll right.
- delta_y
  Integer. Scroll steps in the range `[-127, 127]`; positive values scroll up.


## Returns

- success
  Boolean. `true` if scrolling succeeds; otherwise `false`.
- error_message
  String. The reason scrolling failed.


## Description

> Scroll amounts are not pixels. The system and apps may scale the actual scrolling distance according to their own settings.
> Out-of-range values raise a Lua argument error.


## Example

```lua
local m = assert(mouse.connect())
assert(m:scroll(0, 10))
assert(m:disconnect())
```

---

Source: [LuaSQLite3](https://xxtouch.app/en/docs/handbook/open-source/luasqlite3.md)
Path: handbook/open-source/luasqlite3.md

# LuaSQLite3

[LuaSQLite3 manual](https://lua.sqlite.org/home/doc/tip/doc/lsqlite3.wiki)

---

## Example: require

```lua
local sqlite3 = require('sqlite3')
```

## Example: read iOS SMS database

```lua
local sqlite3 = require('sqlite3')
--
local db = sqlite3.open('/private/var/mobile/Library/SMS/sms.db')
--
local handle_map = {}
local messages = {}
local APPLE_EPOCH_OFFSET = 978307200
--
db:exec('select handle_id, text, date from message', function (ud, ncols, values, names)
    local date_num = tonumber(values[3])
    if date_num > os.time() * (1000^2) then
        date_num = date_num // (1000^3)
    elseif date_num > os.time() * 1000 then
        date_num = date_num // (1000^2)
    elseif date_num > os.time() * 2 then
        date_num = date_num // 1000
    end
    messages[#messages + 1] = {
        handle_id = values[1],
        text = values[2],
        date = os.date("%Y-%m-%d %H:%M:%S", APPLE_EPOCH_OFFSET + date_num)
    }
    return sqlite3.OK
end)
--
db:exec('select ROWID, id from handle', function (ud, ncols, values, names)
    handle_map[values[1]] = values[2]
    return sqlite3.OK
end)
db:close()
--
for _,v in ipairs(messages) do
    v.id = handle_map[v.handle_id]
    v.handle_id = nil
end
--
local results = {}
for _,v in ipairs(messages) do
    results[#results + 1] = string.format("[%s](%s):%s", v.date, v.id, v.text)
end
--
sys.toast(table.concat(results, '\n'))
```
**Note**: Uses [`sys.toast`](/en/docs/handbook/sys/sys.toast.md), [table.concat](https://www.lua.org/manual/5.3/manual.html#pdf-table.concat)

---

Source: [Read all values from a process queue (proc_queue_read)](https://xxtouch.app/en/docs/handbook/proc/proc_queue_read.md)
Path: handbook/proc/proc_queue_read.md

# Read all values from a process queue (proc_queue_read)

## Declaration

```lua
values = proc_queue_read(key)
```

## Parameters

- key
  String.

## Returns

- values
  Array (list). Returns a list containing all values. If the queue does not exist or is empty, returns an empty list.

## Description

- Available for versions after 20250106.
- All process queues whose names start with "xxtouch." or "1ferver." are reserved.
- Read all values from the specified process queue in the process dictionary.

## Example

```lua
local billnos = proc_queue_read("billnos")
if #billnos ~= 0 then
    for i, billno in ipairs(billnos) do
        print(i, billno)
    end
else
    print("no bill")
end
```

---

Source: [Get Color RGB at Point (screen.get_color_rgb)](https://xxtouch.app/en/docs/handbook/screen/screen.get_color_rgb.md)
Path: handbook/screen/screen.get_color_rgb.md

# Get Color RGB at Point (screen.get_color_rgb)

## Declaration

```lua
r, g, b = screen.get_color_rgb(x, y)
```

## Parameters

- x, y
  Integer. Target coordinates.

## Returns

- r, g, b
  Integer. The R/G/B components of the point, range 0~255.

## Description

> Get the color at a screen coordinate and split it into R/G/B components.
> Coordinate parameters follow the coordinate system initialized via [`screen.init`](/en/docs/handbook/screen/screen.init.md).

## Example

```lua
local r, g, b = screen.get_color_rgb(512, 133)
if r==0xff and g==0xff and b==0xff then
    sys.alert("Point 512,133 is pure white")
end
```
**Note**: Uses [`sys.alert`](/en/docs/handbook/sys/sys.alert.md)

---

Source: [Date Formatting (os.date)](https://xxtouch.app/en/docs/handbook/supplement/os.date.md)
Path: handbook/supplement/os.date.md

# Date Formatting (os.date)

The second parameter of [os.date](https://www.lua.org/manual/5.3/manual.html#pdf-os.date) is optional and defaults to the current time.

| Format | Example | Description | Output |
|----|----|----|----|
|%Y-%m-%d %H:%M:%S|os.date("%Y-%m-%d %H:%M:%S", 1487356783)|Common datetime format|2017-02-18 02:39:43|
|%Y-%m-%d|os.date("%Y-%m-%d", 1487356783)|Common date format|2017-02-18|
|%a|os.date("%a", 1487356783)|Abbreviated weekday|Sat|
|%A|os.date("%A", 1487356783)|Full weekday|Saturday|
|%b|os.date("%b", 1487356783)|Abbreviated month|Feb|
|%B|os.date("%B", 1487356783)|Full month|February|
|%c|os.date("%c", 1487356783)|Locale date and time|Sat Feb 18 02:39:43 2017|
|%d|os.date("%d", 1487356783)|Day of month [01-31]|18|
|%H|os.date("%H", 1487356783)|Hour (24h) [00-23]|02|
|%I|os.date("%I", 1487356783)|Hour (12h) [01-12]|02|
|%j|os.date("%j", 1487356783)|Day of year [001-366]|049|
|%M|os.date("%M", 1487356783)|Minute [00-59]|39|
|%m|os.date("%m", 1487356783)|Month [01-12]|02|
|%p|os.date("%p", 1487356783)|AM/PM|AM|
|%S|os.date("%S", 1487356783)|Second [00-61]|43|
|%w|os.date("%w", 1487356783)|Weekday (Sunday=0) [0-6]|6|
|%x|os.date("%x", 1487356783)|Locale date|02/18/17|
|%X|os.date("%X", 1487356783)|Locale time|02:39:43|
|%y|os.date("%y", 1487356783)|Year without century|17|
|%Y|os.date("%Y", 1487356783)|Year with century|2017|
|%%|os.date("%%", 1487356783)|A percent sign|%|

More [os.date](https://www.lua.org/manual/5.3/manual.html#pdf-os.date) usage examples
[`Show current date/time in real-time`](/en/docs/handbook/sys/sys.toast.md)

---

Source: [Get Current Millisecond Timestamp (sys.mtime)](https://xxtouch.app/en/docs/handbook/sys/sys.mtime.md)
Path: handbook/sys/sys.mtime.md

# Get Current Millisecond Timestamp (sys.mtime)

## Declaration

```lua
ts = sys.mtime()
```

## Returns

- ts
  Integer. Millisecond UNIX timestamp.

## Examples

```lua
local ms = sys.mtime()
screen.keep()
sys.alert('Time spent on one screen.keep: '..sys.mtime()-ms..' ms')
```
Note: the example uses [`screen.keep`](/en/docs/handbook/screen/screen.keep.md).

---

Source: [Unregister an event listener (thread.unregister_event)](https://xxtouch.app/en/docs/handbook/thread/thread.unregister_event.md)
Path: handbook/thread/thread.unregister_event.md

# Unregister an event listener (thread.unregister_event)

## Declaration

```lua
thread.unregister_event(event_name, event_id)
```

## Parameters

- event_name
  String.
- event_id
  Integer.

## Description

Unregister an event listener.

## Example

See [the consolidated examples at the end of this chapter](/en/docs/handbook/thread/samples.md)

---

Source: [Set move step length (:step_len)](https://xxtouch.app/en/docs/handbook/touch/touchm_step_len.md)
Path: handbook/touch/touchm_step_len.md

# Set move step length (:step_len)

## Declaration

```lua
te = te:step_len(step)
```

## Parameters

- step
  Integer, optional. Default: 2.

## Returns

- te
  Touch event object itself. You can get a touch event object via [`touch.on`](/en/docs/handbook/touch/touch.on.md).

## Description

- Set the step length when using `:move` to slide.

## Example

```lua
-- Touch at 100,100, slide to 200,200 with step length 3 and per-step delay 0.2 ms, then lift
touch.on(100, 100):step_len(3):step_delay(0.2):move(200, 200):off()
```

---

Source: [Import a Video into Photos (utils.video_to_album)](https://xxtouch.app/en/docs/handbook/utils/utils.video_to_album.md)
Path: handbook/utils/utils.video_to_album.md

# Import a Video into Photos (utils.video_to_album)

## Declaration

```lua
utils.video_to_album(video)
```

## Parameters

- video
  String. Video file path. Supported formats: mp4, m4v, mov.

## Description

> Save mp4/m4v/mov videos to the photo album.

## Examples

```lua
utils.video_to_album("/var/mobile/1.mp4")
```

---

Source: [Disconnect the current VPN (vpnconf.disconnect)](https://xxtouch.app/en/docs/handbook/vpnconf/vpnconf.disconnect.md)
Path: handbook/vpnconf/vpnconf.disconnect.md

# Disconnect the current VPN (vpnconf.disconnect)

## Declaration

```lua
ok = vpnconf.disconnect()
```

## Returns

- ok
  Boolean. true if the operation started successfully (not necessarily disconnected yet); false if the operation failed, usually because no profile is selected.

## Example

```lua
local success = vpnconf.disconnect()
if success then
    sys.alert('Operation succeeded, disconnecting...')
else
    sys.alert('No VPN selected. After creating a VPN, call vpnconf.select to select it.')
end
```
**Note**: Uses [`sys.alert`](/en/docs/handbook/sys/sys.alert.md)

---

Source: [Webview samples](https://xxtouch.app/en/docs/handbook/webview/samples.md)
Path: handbook/webview/samples.md

# Webview samples

## A demo

```lua
local html = [=[
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<!DOCTYPE html>
<html>
    <head>
    <script src="/js/jquery.min.js"></script>
    <script src="/js/jquery.json.min.js"></script>
    <script type="text/javascript">
    $(document).ready(function(){
        $("#toast_content").val("toast content");
        $("#close_page").click(function(){
            $.post(
                "/proc_queue_push",
                '{"key": "msg from webview","value": "close"}',
                function(){}
            );
        });

        $("#show_toast").click(function(){
            $.post(
                "/proc_put",
                $.toJSON({
                    key:"toast content",
                    value:$("#toast_content").val()
                }),
                function(){}
            );
            $.post(
                "/proc_queue_push",
                '{"key": "msg from webview","value": "show toast"}',
                function(){}
            );
        });

        $("#slide_down").click(function(){
            $.post(
                "/proc_queue_push",
                '{"key": "msg from webview","value": "slide down"}',
                function(){}
            );
            $(this).hide();
        });

        $("#full_vertical").click(function(){
            $.post(
                "/proc_queue_push",
                '{"key": "msg from webview","value": "portrait full"}',
                function(){}
            );
        });

        $("#full_landscape").click(function(){
            $.post(
                "/proc_queue_push",
                '{"key": "msg from webview","value": "landscape full"}',
                function(){}
            );
        });
    });
    </script>
    </head>
    <body>
        <p>webview demo</p>
        <p><button id="close_page" type="button">close page</button></p>
        <p><button id="show_toast" type="button">show toast</button><input type="text" id="toast_content" /></p>
        <p><button id="full_vertical" type="button">portrait full</button><button id="full_landscape" type="button">landscape full</button></p>
        <p><button id="slide_down" type="button">slide down</button></p>
        <select>
            <option value="o1">option 1</option>
            <option value="o2">option 2</option>
            <option value="o3">option 3</option>
            <option value="o4">option 4</option>
        </select>
    </body>
</html>
]=]
--
local w, h = screen.size()
local factor = screen.scale_factor()
--
webview.show{ -- reset to top-left
    x = 0,
    y = 0,
    width = w - 40 * factor,
    height = (500) * factor,
    alpha = 0,
    animation_duration = 0,
}
--
webview.show{ -- slide in from top-left in 0.3s
    html = html,
    x = 20 * factor,
    y = 50 * factor,
    width = (w - 40 * factor),
    height = (500) * factor,
    corner_radius = 10,
    alpha = 0.7,
    animation_duration = 0.3,
}
--
proc_queue_clear("msg from webview", "")
local eid = thread.register_event(
    "msg from webview",
    function(val)
        if val == "close" then
            webview.show{
                x = 20 * factor,
                y = 500 * factor * 2,
                width = (w - 40 * factor),
                height = (500 - 70) * factor,
                corner_radius = 10,
                alpha = 0,
                animation_duration = 0.8,
            }
            sys.msleep(800)
            webview.destroy()
            sys.toast("page thread ended")
            return true
        elseif val == "slide down" then
            webview.show{
                x = 20 * factor,
                y = (50 + 300) * factor,
                width = (w - 40  * factor),
                height = (500 - 70) * factor,
                corner_radius = 10,
                alpha = 0.7,
                animation_duration = 0.5,
            }
        elseif val == "portrait full" then
            webview.show{}
        elseif val == "landscape full" then
            webview.show{rotate=90}
        elseif val == "show toast" then
            sys.toast(proc_get("toast content"))
        end
    end
)
--
sys.msleep(3000)
sys.toast("main thread ended")
```

**Note**: Uses [`screen.size`](/en/docs/handbook/screen/screen.size.md), [`proc_queue_clear`](/en/docs/handbook/proc/proc_queue_clear.md), [`thread.register_event`](/en/docs/handbook/thread/thread.register_event.md), [`proc_get`](/en/docs/handbook/proc/proc_get.md), [`sys.toast`](/en/docs/handbook/sys/sys.toast.md), [`sys.msleep`](/en/docs/handbook/sys/sys.msleep.md)

---

Source: [Reload the Currently Displayed Config UI (xui.reload)](https://xxtouch.app/en/docs/handbook/xui/xui.reload.md)
Path: handbook/xui/xui.reload.md

# Reload the Currently Displayed Config UI (xui.reload)

## Declaration

```lua
xui.reload()
```

## Description

> If no configuration UI is currently displayed, nothing happens.
> Be careful with the call frequency; calling too frequently may cause the App to hang.
> See the config UI standard: [XUI](/XUI/README.md)

## Examples

```lua
xui.reload()
```

---

Source: [Terminate an app (app.close)](https://xxtouch.app/en/docs/handbook/app/app.close.md)
Path: handbook/app/app.close.md

# Terminate an app (app.close)

## Declaration

```lua
app.close(bid_or_pid)
```

## Parameters

- bid_or_pid
  String (bundle id) or Integer (pid).

## Description

- Force terminate an app. If the app is not running, nothing happens; the operation does not fail.
- This is a force kill and the target app will not receive any notification.

## Example

- See examples in [`app.run`](/en/docs/handbook/app/app.run.md) and [`app.bundles`](/en/docs/handbook/app/app.bundles.md).

---

Source: [Reset IDFA/V (clear.idfav)](https://xxtouch.app/en/docs/handbook/clear/clear.idfav.md)
Path: handbook/clear/clear.idfav.md

# Reset IDFA/V (clear.idfav)

## Declaration

```lua
oldInfo = clear.idfav([ newInfo ])
```

## Parameters

- newInfo
  String, optional. Provide a specific idfav info string to set as the device's new idfav.
  If omitted, the device's current idfav will be cleared and iOS will re-generate it later.
  Pass "read" to read the current device idfav without clearing.

## Returns

- oldInfo
  String or nil. The device's previous idfav info on success; nil on failure.

## Description

> Reset device identifiers such as IDFA and IDFV.
> If an invalid idfav string is provided, the operation fails and returns nil.
> Without parameters, the current idfav is cleared and iOS will randomly reassign a new one afterward.
> You may save the returned idfav string to a file for later restore by passing it back as the parameter.

## Example

```lua
-- Backup and clear idfav data
app.quit('*') -- close all apps
local old_idfavs = clear.idfav("read") -- read the current idfav data
local ok, err = file.writes(XXT_SCRIPTS_PATH.."/old_idfavs.txt", old_idfavs) -- save the current idfav data to a file
if ok then
    clear.idfav() -- clear idfav data
    sys.alert("Backup succeeded")
else
    sys.alert("Backup failed\n"..tostring(err))
end

-- Restore idfav data from a file
app.quit('*') -- close all apps
local old_idfavs, err = file.reads(XXT_SCRIPTS_PATH.."/old_idfavs.txt") -- read the saved idfav data
if old_idfavs then
    local current_idfavs = clear.idfav(old_idfavs)
    if current_idfavs then
        local ok, err = file.writes(XXT_SCRIPTS_PATH.."/current_idfavs.txt", current_idfavs) -- save the current idfav data to another file
        sys.alert("Successfully restored idfav data")
    else
        sys.alert("Failed to restore idfav data")
    end
else
    sys.alert("Failed to open file\n"..tostring(err))
end
```
**Note**: Uses [`sys.alert`](/en/docs/handbook/sys/sys.alert.md), [`file.reads`](/en/docs/handbook/file/file.reads.md), [`file.writes`](/en/docs/handbook/file/file.writes.md), [`app.quit`](/en/docs/handbook/app/app.quit.md)

---

Source: [Unlock rotation lock (device.unlock_orien)](https://xxtouch.app/en/docs/handbook/device/device.unlock_orien.md)
Path: handbook/device/device.unlock_orien.md

# Unlock rotation lock (device.unlock_orien)

## Declaration

```lua
device.unlock_orien()
```

## Example

```lua
device.unlock_orien()
```

---

Source: [Set dialog corner radius (:set_corner_radius)](https://xxtouch.app/en/docs/handbook/dialog/dialogm_set_corner_radius.md)
Path: handbook/dialog/dialogm_set_corner_radius.md

# Set dialog corner radius (:set_corner_radius)

## Declaration

```lua
dialog_obj = dialog_obj:set_corner_radius(radius)
```

## Parameters

- radius
  Integer. Corner radius. 0 means square corners

## Returns

- dialog_obj
  Dialog. Returns the dialog itself

## Description

> Configure the dialog's corner radius. Useful when a rounded dialog is desired.
> This method works only for dialogs that use the webview engine.

## Example

```lua
local dlg = dialog()
dlg:set_frame(0, 0, 600, 800)
dlg:set_corner_radius(50)
dlg:show()
```

---

Source: [Count total lines in a text file (file.line_count)](https://xxtouch.app/en/docs/handbook/file/file.line_count.md)
Path: handbook/file/file.line_count.md

# Count total lines in a text file (file.line_count)

## Declaration

```lua
count = file.line_count(path)
```

## Parameters

- path
  String. Absolute file path.

## Returns

- count
  Integer or nil. Total number of lines. 0 for empty file. nil if file does not exist.

## Description

> Count total lines in a text file. Empty file returns 0.

## Example

```lua
local linecount = file.line_count("/var/mobile/1.txt")
if linecount then
    sys.alert("/var/mobile/1.txt has "..linecount.." lines")
else
    sys.alert("/var/mobile/1.txt is not a file")
end
```
**Note**: Uses [`sys.alert`](/en/docs/handbook/sys/sys.alert.md)

---

Source: [Reset gamepad state (:reset)](https://xxtouch.app/en/docs/handbook/gamepad/gamepadm_reset.md)
Path: handbook/gamepad/gamepadm_reset.md

# Reset gamepad state (:reset)

> **This method is available in versions after 20260805**

## Declaration

```lua
success, err = pad:reset()
```

## Returns

- success
  Boolean. True if the reset succeeds; false if the device is disconnected or busy, or if input delivery fails
- err
  String. Error message when the operation fails

## Description

> Releases all buttons and centers both analog sticks and the directional pad.

## Example

```lua
local pad = assert(gamepad.connect())

assert(pad:set_stick("left", 1, 0))
assert(pad:reset())
assert(pad:disconnect())
```

---

Source: [Send PUT request (http.put)](https://xxtouch.app/en/docs/handbook/http/http.put.md)
Path: handbook/http/http.put.md

# Send PUT request (http.put)

## Declaration

```lua
code, res_headers_json, body = http.put(URL [, timeout_secs, headers, data, url_no_escape])
```

## Declaration (named arguments)

**Supported since 2025-06-25; progress options are supported since 2026-04-02**
```lua
code, res_headers_json, body = http.put{
    url = URL;
    timeout = timeout_secs;
    headers = headers;
    params = query_params;

    -- The following body options are mutually exclusive, priority: multipart > data > json > upload_file
    multipart = multipart_form;
    data = body_data;
    json = body_json;
    upload_file = upload_file_path;

    download_file = save_response_body_file_path;
    progress = progress_callback;
    progress_interval_ms = progress_interval_ms;
}
```

## Parameters

- URL
  String. Request URL. The function escapes the URL by default; see "url_no_escape" if you don't want this.
- timeout_secs
  Number, optional. Timeout in seconds. Default 10.
- headers
  Table, optional. Request headers in the form `{ field1 = value1, ... }`. Default `{}`.
- query_params
  Table, optional. Query string parameters in the form `{ field1 = value1, ... }`. Default `{}`.
- body_data
  String or Table, optional. Request body.
  Since 2025-06-25, if a table is provided, it is encoded as application/x-www-form-urlencoded.
- multipart_form
  Table, optional. Multipart form data to send.
- body_json
  Table, optional. Body encoded as application/json.
- upload_file_path
  String, optional. Send file content directly as body.
- save_response_body_file_path
  String, optional. If provided, the returned body is the saved file path on success.
- progress_callback
  Function, optional. Supported since 2026-04-02. Called when upload or download progress changes. The first argument is the current progress info.
- progress_interval_ms
  Integer, optional. Supported since 2026-04-02. Progress callback interval in milliseconds.
- url_no_escape
  Boolean, optional. true = do not escape URL. Default false.
  For custom escaping, see the [`lcurl` module](/en/docs/handbook/open-source/lcurl.md) [easy:escape](https://lua-curl.github.io/lcurl/modules/lcurl.html#easy:escape) and [easy:unescape](https://lua-curl.github.io/lcurl/modules/lcurl.html#easy:unescape).

## Returns

- code
  Integer. HTTP status code. -1 on timeout.
- res_headers_json
  String or nil. Response headers in JSON. nil on timeout.
- body
  String or nil. Response body. If saved to file, this is the file path. nil on timeout.

## Description

> Use HTTP/1.1 PUT method to send data; usage is similar to POST.
> This function may yield; other [threads](/en/docs/handbook/thread/index.md) may run before it returns.

The `info` table passed to the progress callback has this structure:

```lua
{
    count_of_bytes_sent = bytes_sent;
    count_of_bytes_expected_to_send = bytes_expected_to_send;
    count_of_bytes_received = bytes_received;
    count_of_bytes_expected_to_receive = bytes_expected_to_receive;
}
```

## Example

```lua
local code, res_headers, body = http.put("https://httpbin.org/put?hello=world&你好=世界", 15, {
    ["User-Agent"] = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0)",
    ["Cookie"] = "a=1; b=2; c=3";
}, "data to send")
if code == 200 then
    sys.alert(body)
end
```
**Note**: Uses [`sys.alert`](/en/docs/handbook/sys/sys.alert.md)

## Example (named arguments)

```lua
local code, res_headers, body = http.put{
    url = "https://httpbin.org/put";
    timeout = 15;
    headers = {
        ["User-Agent"] = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0)";
        ["Cookie"] = "a=1; b=2; c=3";
    };
    params = {
        ["hello"] = "world";
        ["你好"] = "世界";
    };
    data = "data to send";
}
if code == 200 then
    sys.alert(body)
end
```
**Note**: Uses [`sys.alert`](/en/docs/handbook/sys/sys.alert.md)

---

Source: [Create a copy of an image object (:copy)](https://xxtouch.app/en/docs/handbook/image/imagem_copy.md)
Path: handbook/image/imagem_copy.md

# Create a copy of an image object (:copy)

## Declaration

```lua
img_copy = img:copy()
```

## Returns

- img_copy
  Image object. A copy of the original image

## Description

> Create a copy from an image object
> This call creates a new image object. For efficient frequent usage, please pair with [image:destroy](/en/docs/handbook/image/imagem_destroy.md)

## Example

```lua
scrn = screen.image()
img2 = scrn:copy()
```
Note: This example uses a function outside this chapter [`screen.image`](/en/docs/handbook/screen/screen.image.md)

---

Source: [! Connect a global hardware keyboard (key.connect_global_keyboard)](https://xxtouch.app/en/docs/handbook/key/key.connect_global_keyboard.md)
Path: handbook/key/key.connect_global_keyboard.md

# ! Connect a global hardware keyboard (key.connect_global_keyboard)

> **This function is available in versions after 20260805**

## Declaration

```lua
keyboard, err = key.connect_global_keyboard([properties])
```

## Parameters

- properties
  Table. Optional. Uses the same default properties and constraints as [`key.connect_keyboard`](key.connect_keyboard.md).

## Returns

- keyboard
  Hardware keyboard object. Returns `nil` if the connection fails.
- err
  String. Error message returned when the connection fails.

On failure, the two return values are `nil, error`.

## Description

> Create and connect the global hardware keyboard. Waiting for the connection may yield; other [threads](/en/docs/handbook/thread/index.md) may run before the function returns.

- After connection, standard keyboard and keypad input from `key.press`, `key.down`, `key.up`, `key.send_text`, and `key(...):press/down/up` uses this object
- Media and vendor-defined keys keep their previous behavior
- When no global hardware keyboard is connected, the existing APIs behave as before.
- A `key.down` call remains paired with its matching `key.up` even if the connection changes between the calls, preventing duplicate input or an incorrect release
- Only one global hardware keyboard may be connected at a time. Calling this function again while a connection is in progress or while a global keyboard is already connected returns a failure.

## Example

```lua
local keyboard, err = key.connect_global_keyboard({
    Product = "XXTouch Keyboard",
})
assert(keyboard, err)

key.press("A")
key.send_text("Hello")

local current = key.get_global_keyboard()
assert(current == keyboard)

assert(key.disconnect_global_keyboard())
```

---

Source: [Get the hardware mouse connection state (:is_connected)](https://xxtouch.app/en/docs/handbook/mouse/mousem_is_connected.md)
Path: handbook/mouse/mousem_is_connected.md

# Get the hardware mouse connection state (:is_connected)

> **This method is available in versions after 20260805**


## Declaration

```lua
connected = mouse_obj:is_connected()
```


## Returns

- connected
  Boolean. `true` while the hardware mouse remains connected; otherwise `false`.


## Description

> Get the current connection state of the hardware mouse object.


## Example

```lua
local m = assert(mouse.connect())
assert(m:is_connected())
assert(m:disconnect())
assert(not m:is_connected())
```

---

Source: [lcurl](https://xxtouch.app/en/docs/handbook/open-source/lcurl.md)
Path: handbook/open-source/lcurl.md

# lcurl

[lcurl manual](https://lua-curl.github.io/lcurl/modules/lcurl.html)

---

## URL percent-encode / decode (escape / unescape)

> Keywords: URL encode, URI encode, percent-encoding, URLEncode, URLDecode, URLEscape, PercentEscape

```lua
local curl = require('lcurl')
local e = curl.easy()
--
print(e:escape('abcd$%^&*()'))                 -- outputs "abcd%24%25%5E%26%2A%28%29"
--
print(e:unescape('abcd%24%25%5E%26%2A%28%29')) -- outputs "abcd$%^&*()"
--
sys.alert(print.out())
```
**Note**: Uses [`sys.alert`](/en/docs/handbook/sys/sys.alert.md)

## Example: httpGet implemented with lcurl

```lua
function httpGet(url) -- also works for ftp (this function is built-in; shown here only as lcurl usage)
    if (url:sub(1, 6) ~= "ftp://" and
        url:sub(1, 8) ~= "https://" and
        url:sub(1, 7) ~= "http://") then
        url = "https://"..url
    end
    local curl = require("curl.safe")
    local buffer_t = {}
    local write_f = function(s)
        buffer_t[#buffer_t + 1] = s
    end
    local noerr, err = pcall(function()
        curl.easy()
            :setopt(curl.OPT_URL, url)
            :setopt(curl.OPT_CONNECTTIMEOUT, 60)
            :setopt_writefunction(write_f)
        :perform()
    end)
    if (noerr) then
        return table.concat(buffer_t)
    else
        return nil, err
    end
end
```
**Note**: Uses [table.concat](https://www.lua.org/manual/5.3/manual.html#pdf-table.concat)

---

Source: [Get size of process queue (proc_queue_size)](https://xxtouch.app/en/docs/handbook/proc/proc_queue_size.md)
Path: handbook/proc/proc_queue_size.md

# Get size of process queue (proc_queue_size)

## Declaration

```lua
size = proc_queue_size(key)
```

## Parameters

- key
  String.

## Returns

- size
  Integer. Number of valid entries in the process queue.

## Description

- All process queues whose names start with "xxtouch." or "1ferver." are reserved.
- Get the size of the queue.

## Example

```lua
local size = proc_queue_size("billnos")
if size ~= 0 then
    print("has "..size.." bill(s)")
else
    print("no bill")
end
```

---

Source: [Multi-point Color Match (screen.is_colors)](https://xxtouch.app/en/docs/handbook/screen/screen.is_colors.md)
Path: handbook/screen/screen.is_colors.md

# Multi-point Color Match (screen.is_colors)

## Declaration

```lua
matched = screen.is_colors({
    [max_miss = integer_value,]
    [xy_tolerance = integer_value,]
    [csim_algorithm = integer_value,]
    {x1, y1, color1},
    {x2, y2, color2},
    ...
}[, similarity])
```

## Parameters

- max_miss
  Integer, optional. Maximum number of non-matching points allowed. Default 0 (all points must match).
- xy_tolerance (since 2025-02-28)
  Integer, optional. Allowed coordinate deviation; points exceeding this offset are treated as miss. Default 0.
- csim_algorithm (since 2025-03-02)
  Integer, optional. Color similarity algorithm. Default 0.
  <details>
  <summary>Algorithms</summary>

  ```lua
  0 = XXT default (steep gradient, similarity drops quickly with difference)
  1 = Manhattan (smooth)
  2 = Euclidean (smooth)
  ```
  </details>
- x, y
  Integer. Coordinate of a point.
- color
  Integer. Expected color value of the point.
- similarity
  Integer, optional. Similarity threshold shared by all points when individual similarity is not specified. Range 1~100, default 100.

## Returns

- matched
  Boolean. true if all points match under the rules, otherwise false.

## Description

> Match colors of several points on the screen.
> Coordinate parameters follow the coordinate system initialized via [`screen.init`](/en/docs/handbook/screen/screen.init.md).

## Example

```lua
if screen.is_colors({
    { 509, 488, 0xec1c23},
    { 514, 470, 0x00adee},
    { 508, 478, 0xffc823},
    { 511, 454, 0xa78217},
    { 521, 433, 0xd0d2d2},
}, 90) then
    sys.alert("Matched!")
else
    sys.alert("Not matched!")
end
```
**Note**: Uses [`sys.alert`](/en/docs/handbook/sys/sys.alert.md)

---

Source: [Command Execution Sample Code (os.execute)](https://xxtouch.app/en/docs/handbook/supplement/os.execute.md)
Path: handbook/supplement/os.execute.md

# Command Execution Sample Code (os.execute)

`os.execute` depends on the shell; in a jailbroken iOS environment the shell might be `bash` or `zsh`.
The XXTouch TrollStore build cannot use `os.execute`.
Avoid `os.execute` whenever possible.

## Reboot device

```lua
-- os.execute('reboot')
-- Use the following call instead
sys.reboot()
```

## Respring device

```lua
-- os.execute('killall -9 SpringBoard;killall -9 backboardd')
-- Use the following call instead
sys.killall(9, 'SpringBoard', 'backboardd')
```

## Rebuild icon cache

```lua
-- os.execute('su mobile -c uicache')
-- Use the following call instead
clear.caches()
```

## Create a script log symlink in the script directory

```lua
-- os.execute('ln -s /private/var/mobile/Media/1ferver/log/sys.log /private/var/mobile/Media/1ferver/lua/scripts/script-log.txt')
-- Use the following call instead
lfs.link('/private/var/mobile/Media/1ferver/log/sys.log', '/private/var/mobile/Media/1ferver/lua/scripts/script-log.txt', true)
```

## Common helper functions

```lua
--[[
    The following wrappers are no longer recommended.
    Use the built-in XXTouch file module functions instead.
--]]

local function sh_escape(path) -- XXTouch original function; you may use it commercially without XXTouch's permission
    path = string.gsub(path, "([ \\()<>\'\"`#&*;?~$|])", "\\%1")
    return path
end

function fdelete(path) -- Delete a file or directory (recursively delete children)
    assert(type(path)=="string" and path~="", 'fremove argument error')
    -- os.execute('rm -rf '..sh_escape(path))
    -- Use the following call instead
    file.remove(path)
end

function frename(from, to) -- Rename (move) a file or directory
    assert(type(from)=="string" and from~="", 'frename arg #1 error')
    assert(type(to)=="string" and to~="", 'frename arg #2 error')
    -- os.execute('mv -f '..sh_escape(from).." "..sh_escape(to))
    -- Use the following call instead
    file.move(from, to, 'mo')
end

function fcopy(from, to) -- Copy a file or directory (recursively copy children)
    assert(type(from)=="string" and from~="", 'fcopy arg #1 error')
    assert(type(to)=="string" and to~="", 'fcopy arg #2 error')
    -- os.execute('cp -rf '..sh_escape(from).." "..sh_escape(to))
    -- Use the following call instead
    file.copy(from, to, 'mo')
end

function mkdir(path) -- Create a directory (recursively create parents)
    assert(type(path)=="string" and path~="", 'mkdir argument error')
    -- os.execute('mkdir -p '..sh_escape(path))
    -- Use the following call instead
    file.mkdir_p(path)
end

-- Copy the wrapped functions above into your script before using them.
-- The following shows how to call them (no need to copy).

-- Delete /var/mobile/1.png
fdelete("/var/mobile/1.png")

-- Rename /var/mobile/2.png to /var/mobile/1.png
frename("/var/mobile/2.png", "/var/mobile/1.png")

-- Move /var/mobile/1.png to /var/mobile/Media/1ferver/res/3.png
frename("/var/mobile/1.png", "/var/mobile/Media/1ferver/res/3.png")

-- Copy /var/mobile/1.png to /var/mobile/Media/1ferver/res/4.png
fcopy("/var/mobile/1.png", "/var/mobile/Media/1ferver/res/4.png")

-- Create directory /var/mobile/1/2/3/4
mkdir("/var/mobile/1/2/3/4")

```

---

Source: [Get Network Time (sys.net_time)](https://xxtouch.app/en/docs/handbook/sys/sys.net_time.md)
Path: handbook/sys/sys.net_time.md

# Get Network Time (sys.net_time)

## Declaration

```lua
sec_ts = sys.net_time([ timeout ])
```

## Parameters

- timeout
  Number. Optional. Max wait time for networking in seconds. Default: 2.

## Returns

- sec_ts
  Integer. Second-level UNIX timestamp of current network time. Returns 0 on timeout or failure.

## Description

> This method may yield; other [threads](/en/docs/handbook/thread/index.md) may run before it returns.

## Examples

```lua
local nt = sys.net_time() -- default 2s timeout, returns 0 on timeout
--
local nt = sys.net_time(5) -- 5s timeout
if nt==0 then
    sys.alert('Failed to get network time')
else
    sys.alert(os.date('Network time\n%Y-%m-%d %H:%M:%S', nt))
end
```
Note: uses [os.date formatting](/en/docs/handbook/supplement/os.date.md).

---

Source: [thread sample code](https://xxtouch.app/en/docs/handbook/thread/samples.md)
Path: handbook/thread/samples.md

# thread sample code

```lua
tmid = thread.dispatch( -- dispatch an async task
    function()
        sys.msleep(2700)
        sys.toast("This is the 2.7th second")
    end
)
--
tid = thread.dispatch( -- dispatch another async task
    function()
        sys.msleep(300)
        for i=1,10 do
            sys.toast("Thread 2: "..i)
            sys.msleep(1000)
        end
        sys.toast("Should not reach here")
    end
)
--
-- iPhone 5C pinch-in in Photos example
--
thread.dispatch(function() -- dispatch a swipe task
    touch.on(59,165)
        :move(297,522)
        :msleep(500)
    :off()
end)
--
thread.dispatch(function() -- dispatch another swipe task
    touch.on(580,1049)
        :move(371,1049)
        :msleep(500)
    :off()
end)
--
proc_queue_clear("message-from-far-away")
eid = thread.register_event( -- register listener for "dictionary has value" event
    "message-from-far-away",
    function(val)
        sys.toast("Received message: "..val)
    end
)
--
sys.msleep(300)
thread.wait(tmid)
--
for i=1,10 do
    sys.toast("Thread 1: "..i)
    sys.msleep(400)
end
--
thread.kill(tid) -- kill Thread 2
thread.unregister_event("message-from-far-away", eid) -- unregister the event listener
--
sys.toast("Done")
```

**Note**: The code above uses functions and methods from other chapters: [`proc_queue_clear`](/en/docs/handbook/proc/proc_queue_clear.md), [`sys.msleep`](/en/docs/handbook/sys/sys.msleep.md), [`sys.toast`](/en/docs/handbook/sys/sys.toast.md), [`touch.on`](/en/docs/handbook/touch/touch.on.md), [`:move`](/en/docs/handbook/touch/touchm_move.md), [`:msleep`](/en/docs/handbook/touch/touchm_msleep.md), [`:off`](/en/docs/handbook/touch/touchm_off.md)

---

Source: [Set per-step move delay (:step_delay)](https://xxtouch.app/en/docs/handbook/touch/touchm_step_delay.md)
Path: handbook/touch/touchm_step_delay.md

# Set per-step move delay (:step_delay)

## Declaration

```lua
te = te:step_delay(ms)
```

## Parameters

- ms
  Number, optional. Per-step delay in milliseconds. Default: 0.1.

## Returns

- te
  Touch event object itself. You can get a touch event object via [`touch.on`](/en/docs/handbook/touch/touch.on.md).

## Description

- Set the per-step delay when using `:move` to slide.

## Example

```lua
-- Touch at 100,100, slide to 200,200 with step length 3 and per-step delay 0.2 ms, then lift
touch.on(100, 100):step_len(3):step_delay(0.2):move(200, 200):off()
```

---

Source: [Generate a UUID (utils.gen_uuid)](https://xxtouch.app/en/docs/handbook/utils/utils.gen_uuid.md)
Path: handbook/utils/utils.gen_uuid.md

# Generate a UUID (utils.gen_uuid)

## Declaration

```lua
uuid = utils.gen_uuid()
```

## Returns

- uuid
  String. Generated UUID.

## Description

> Available since 1.3.8.

## Examples

```lua
nLog(utils.gen_uuid())
```

---

Source: [Get status of selected VPN (vpnconf.status)](https://xxtouch.app/en/docs/handbook/vpnconf/vpnconf.status.md)
Path: handbook/vpnconf/vpnconf.status.md

# Get status of selected VPN (vpnconf.status)

## Declaration

```lua
status = vpnconf.status()
```

## Returns

- status
  Table or nil. On success, returns a status table; returns nil if no VPN is selected.

  <details>
  <summary>Returned status table</summary>

  ```lua
  {
      text = textual description of the current status,
      connected = whether the VPN is connected,
  }
  ```
  </details>

## Example

```lua
local status = vpnconf.status()
if status then
    sys.alert(table.deep_dump(status))
else
    sys.alert('No VPN selected. After creating a VPN, call vpnconf.select to select it.')
end
```
**Note**: Uses [`sys.alert`](/en/docs/handbook/sys/sys.alert.md), [`table.deep_dump`](/en/docs/handbook/ext-table/table.deep_dump.md)

---

Source: [Get a Config Value from the UI (xui.get)](https://xxtouch.app/en/docs/handbook/xui/xui.get.md)
Path: handbook/xui/xui.get.md

# Get a Config Value from the UI (xui.get)

## Declaration

```lua
value = xui.get(domain, key)
```

## Parameters

- domain
  String. The defaults domain identifier used by the config UI.
- key
  String. The control's key identifier in the config UI.

## Returns

- value
  Any. Different control types return different value types. Returns nil if the value does not exist.

## Description

> This function does not validate value types. If you need to ensure the retrieved value matches the control's expected type, call `xui.setup` first to validate/correct and then read.
> See the config UI standard: [XUI](/XUI/README.md)

## Examples

```lua
xui.setup('interface.xui')
local enabled = xui.get('com.yourcompany.A-Script-Bundle', 'enabled')
```

---

Source: [Simulate swipe-up quit (app.quit)](https://xxtouch.app/en/docs/handbook/app/app.quit.md)
Path: handbook/app/app.quit.md

# Simulate swipe-up quit (app.quit)

## Declaration

```lua
app.quit(bid)
```

## Parameters

- bid
  String. App bundle identifier. Use "*" to quit all. Bundle id can be found in `XXT App -> More -> App List`.

## Description

- Also a force quit, but unlike [`app.close`](/en/docs/handbook/app/app.close.md), the app receives a notification and has up to 10 seconds to save data before being fully terminated. It also clears the app's multitasking card.
- Do NOT use while the screen is locked. It may fail to quit apps running with root privileges and could freeze the UI; for root apps, prefer [`app.close`](/en/docs/handbook/app/app.close.md).

## Example

```lua
-- Quit all apps
app.quit("*")
-- Quit QQ if it is running
app.quit("com.tencent.mqq")
```

---

Source: [Is rotation lock enabled (device.is_orien_locked)](https://xxtouch.app/en/docs/handbook/device/device.is_orien_locked.md)
Path: handbook/device/device.is_orien_locked.md

# Is rotation lock enabled (device.is_orien_locked)

## Declaration

```lua
locked = device.is_orien_locked()
```

## Returns

- locked
  Boolean. Whether screen rotation is locked

## Example

```lua
if device.is_orien_locked() then
    -- rotation is locked
else
    -- rotation is not locked
end
```

---

Source: [Add a text label (:add_label)](https://xxtouch.app/en/docs/handbook/dialog/dialogm_add_label.md)
Path: handbook/dialog/dialogm_add_label.md

# Add a text label (:add_label)

## Declaration

```lua
dialog_obj = dialog_obj:add_label(text)
```

## Parameters

- text
  String. The label text

## Returns

- dialog_obj
  Dialog. Returns the dialog itself

## Description

> Add a text label to the dialog

## Example

```lua
dialog():add_label('A text label'):show()
```

## Full example

See [:show()](/en/docs/handbook/dialog/dialogm_show.md)

---

Source: [Get a specific line from a text file (file.get_line)](https://xxtouch.app/en/docs/handbook/file/file.get_line.md)
Path: handbook/file/file.get_line.md

# Get a specific line from a text file (file.get_line)

## Declaration

```lua
line, err = file.get_line(path, n)
```

## Parameters

- path
  String. Absolute file path.
- n
  Integer. Line number. 0 means last line + 1. Negative means counting from the end.

## Returns

- line
  String or nil. Empty string if line number is out of range. nil if file does not exist.
- err
  String. Error message when operation fails.

## Description

> Get a specific line from a text file.
> This function automatically strips UTF-8 BOM at the file head.

## Example

```lua
local data, err = file.get_line("/var/mobile/1.txt", 1)
if data then
    sys.alert("First line of /var/mobile/1.txt is "..data)
else
    sys.alert("Read failed: "..err)
end
```
**Note**: Uses [`sys.alert`](/en/docs/handbook/sys/sys.alert.md)

---

Source: [Check whether a gamepad is connected (:is_connected)](https://xxtouch.app/en/docs/handbook/gamepad/gamepadm_is_connected.md)
Path: handbook/gamepad/gamepadm_is_connected.md

# Check whether a gamepad is connected (:is_connected)

> **This method is available in versions after 20260805**

## Declaration

```lua
connected = pad:is_connected()
```

## Returns

- connected
  Boolean. True while the gamepad device remains connected; otherwise false

## Description

> Checks whether this gamepad object is still connected.

## Example

```lua
local pad = assert(gamepad.connect())
assert(pad:is_connected())
assert(pad:disconnect())
```

---

Source: [Encode application/x-www-form-urlencoded (http.table_to_form_urlencoded)](https://xxtouch.app/en/docs/handbook/http/http.table_to_form_urlencoded.md)
Path: handbook/http/http.table_to_form_urlencoded.md

# Encode application/x-www-form-urlencoded (http.table_to_form_urlencoded)

## Declaration

```lua
encoded = http.table_to_form_urlencoded(tbl)
```

## Parameters

- tbl
  Table.

## Returns

- encoded
  String.

## Description

> Available since 2025-03-13.

## Example

```lua
form = http.table_to_form_urlencoded{
    num = 1,
    str = '你好',
    arr = {12, 34, '好'},
}

nLog(form) -- arr%5B0%5D=12&arr%5B1%5D=34&arr%5B2%5D=%E5%A5%BD&str=%E4%BD%A0%E5%A5%BD&num=1

c, h, r = http.get('https://httpbin.org/get?'..form, 10, {}, true) -- Submit via GET query; URL is auto-escaped by default unless the last arg is true
nLog(r)

c, h, r = http.post('https://httpbin.org/post', 10, {}, form) -- Submit via POST
nLog(r)
```

---

Source: [Crop a region from an image to create a new image (:crop)](https://xxtouch.app/en/docs/handbook/image/imagem_crop.md)
Path: handbook/image/imagem_crop.md

# Crop a region from an image to create a new image (:crop)

## Declaration

```lua
cropped = img:crop([left, top, right, bottom])
```

## Parameters

- left, top, right, bottom
  Integer, optional. Region coordinates in the original image. Default 0, 0, img_width-1, img_height-1

## Returns

- cropped
  Image object. The cropped image

## Description

> Create a cropped copy from an existing image object
> This call creates a new image object. For efficient frequent usage, please pair with [image:destroy](/en/docs/handbook/image/imagem_destroy.md)

## Example

```lua
scrn = screen.image()
img2 = scrn:crop(100, 100, 200, 200)
```
Note: This example uses a function outside this chapter [`screen.image`](/en/docs/handbook/screen/screen.image.md)

---

Source: [Get the current global hardware keyboard (key.get_global_keyboard)](https://xxtouch.app/en/docs/handbook/key/key.get_global_keyboard.md)
Path: handbook/key/key.get_global_keyboard.md

# Get the current global hardware keyboard (key.get_global_keyboard)

> **This function is available in versions after 20260805**

## Declaration

```lua
keyboard = key.get_global_keyboard()
```

## Returns

- keyboard
  The currently connected global hardware keyboard object, or `nil` when no object is available.

## Description

> Call `key.get_global_keyboard()` to get the global hardware keyboard object connected by [`key.connect_global_keyboard`](key.connect_global_keyboard.md).

This function returns `nil` when no keyboard is connected, while a connection is in progress, or after the device has disconnected.

## Example

```lua
local keyboard = key.get_global_keyboard()
if keyboard then
    assert(keyboard:press("RETURN"))
end
```

---

Source: [Get the hardware mouse creation properties (:get_properties)](https://xxtouch.app/en/docs/handbook/mouse/mousem_get_properties.md)
Path: handbook/mouse/mousem_get_properties.md

# Get the hardware mouse creation properties (:get_properties)

> **This method is available in versions after 20260805**


## Declaration

```lua
properties = mouse_obj:get_properties()
```


## Returns

- properties
  Table. A copy of the configuration properties saved when the device was created.


## Description

> Returns the configuration saved at creation time, which may include system-managed properties. This is not live system state, and the values ultimately used by iOS may differ.


## Example

```lua
local m = assert(mouse.connect())
local properties = m:get_properties()
print(properties.Product)
print(properties.Transport)
assert(m:disconnect())
```

---

Source: [lunix](https://xxtouch.app/en/docs/handbook/open-source/lunix.md)
Path: handbook/open-source/lunix.md

# lunix

[lunix manual](/pdf/lunix.pdf)

---

## Change file owner and mode

```lua
local unix = require("unix")
unix.chown("/var/mobile/Media/1ferver/1ferver.conf", 501, 501)
unix.chmod("/var/mobile/Media/1ferver/1ferver.conf", 6 * 8^2 + 4 * 8^1 + 4 * 8^0)
```

---

Source: [Push to front of process queue (proc_queue_push_front)](https://xxtouch.app/en/docs/handbook/proc/proc_queue_push_front.md)
Path: handbook/proc/proc_queue_push_front.md

# Push to front of process queue (proc_queue_push_front)

## Declaration

```lua
size = proc_queue_push_front(key, value)
```

## Parameters

- key
  String.
- value
  String. The value to push.

## Returns

- size
  Integer. Size after pushing. If 0, push failed.

## Description

- All process queues whose names start with "xxtouch." or "1ferver." are reserved.
- Queue size must not exceed 10000; exceeding values will drop earliest entries.
- Push a value to the front and return the size.
- Empty string cannot be pushed.

## Example

```lua
local size = proc_queue_push_front("billnos", "name")
if size ~= 0 then
    print("has "..size.." bill(s)")
else
    print("failed")
end
```

---

Source: [Find Color - Color Similarity Mode (screen.find_color)](https://xxtouch.app/en/docs/handbook/screen/screen.find_color-cs.md)
Path: handbook/screen/screen.find_color-cs.md

# Find Color - Color Similarity Mode (screen.find_color)

## Declaration

```lua
x, y = screen.find_color({
    [find_all = boolean,]
    [max_results = integer_value,]
    [max_miss = integer_value,]
    [csim_algorithm = integer_value,]
    {x0, y0, color0[, sim0]},
    {dx*, dy*, color*[, sim*]},
    {dx*, dy*, color*[, sim*]},
    ...
}[, global_similarity, left, top, right, bottom ])
```

## Parameters

- find_all
  Boolean, optional. When true, returns a table of all match positions within the region, format `{{x1, y1}, {x2, y2}, ...}`. Default false.
- max_results
  Integer, optional. The maximum number of results when `find_all` is true. Up to 1000, default 100.
- max_miss
  Integer, optional. Maximum number of non-matching points allowed. Default 0 (all points must match).
- csim_algorithm (2025-03-02)
  Integer, optional. Color similarity algorithm, default 0.
  <details>
  <summary>Algorithms</summary>

  ```lua
  0 = XXT default (steep gradient, similarity drops quickly with difference)
  1 = Manhattan (smooth)
  2 = Euclidean (smooth)
  ```
  </details>
- x0, y0
  Integer. Starting anchor coordinate. This establishes a reference point for calculating offset positions, not a search boundary. If unsure, use 0, 0.
- color0
  Integer. Color to match at the starting point.
- sim0
  Integer, optional. Similarity for the starting point. Range 1~100, default 100.
- dx*, dy*
  Integer. Offset coordinate relative to the starting point.
- color*
  Integer. Expected color at the offset point.
- sim*
  Integer, optional. Similarity for the offset point. Range -100~100, default 100. Negative value means match similarity less than its absolute value (inverse match).
- global_similarity
  Integer, optional. Used for all points if no per-point similarity is provided. Range 1~100, default 100.
- left, top, right, bottom
  Integer, optional. Search region. Default is full screen.

## Returns

- x, y
  Integer. The coordinate of the first matched multi-point structure. Returns -1, -1 on failure.

## Description

> Find the position of the first fully matched multi-point color structure using similarity mode.
> Coordinate parameters and return values follow the coordinate system initialized via [`screen.init`](/en/docs/handbook/screen/screen.init.md).

## Example

```lua
x, y = screen.find_color({
    {  0,   0, 0xec1c23},
    { 12,  -3, 0xffffff, 85},
    {  5, -18, 0x00adee},
    { -1, -10, 0xffc823},
    {  2, -34, 0xa78217},
    { 12, -55, 0xd0d2d2},
}, 90, 0, 0, 100, 100)
--
-- Equivalent form with absolute coords:
--
x, y = screen.find_color({
    { 509, 488, 0xec1c23},
    { 521, 485, 0xffffff, 85},
    { 514, 470, 0x00adee},
    { 508, 478, 0xffc823},
    { 511, 454, 0xa78217},
    { 521, 433, 0xd0d2d2},
}, 90, 0, 0, 100, 100)
--
-- One-line compact form:
--
x, y = screen.find_color({ {0,0,0xec1c23},{12,-3,0xffffff,85},{5,-18,0x00adee},{-1,-10,0xffc823},{2,-34,0xa78217},{12,-55,0xd0d2d2},},90,0,0,100,100)
--
-- Inverse matching demo (run on iPhone 5C home screen for results):
x, y = screen.find_color({
    { 516,  288, 0xffffff },
    { 519,  286, 0xffffff },
    { 521,  289, 0xffffff },
    { 516,  296, 0xffffff },
    { 522,  297, 0xffffff },
    { 520,  295, 0xffffff, -10 }, -- match similarity less than 10
    { 515,  291, 0xffffff, -10 },
    { 518,  284, 0xffffff, -10 },
    { 523,  298, 0xffffff, -10 },
    { 514,  298, 0xffffff, -10 },
    { 514,  296, 0xffffff, -10 },
}, 90)
--
-- Find-all demo (returns all positions):
results = screen.find_color({
    {  527,  278, 0xde1d26 },
    {  524,  285, 0x007aff },
    {  555,  292, 0xe4ddc9 },
    {  536,  314, 0xffde02 },
    {  502,  291, 0xffde02 },
    {  502,  283, 0xe4ddc9 },
    find_all = true,
}, 90)
```

---

Source: [Applications of the string Library](https://xxtouch.app/en/docs/handbook/supplement/string-samples.md)
Path: handbook/supplement/string-samples.md

# Applications of the string Library

## Basic functions

| Function | Description | Example | Result |
|----|----|----|----|
|len|String length|string.len("abcd")|4|
|rep|Repeat string n times|string.rep("abcd",2)|abcdabcd|
|lower|To lowercase|string.lower("AbcD")|abcd|
|upper|To uppercase|string.upper("AbcD")|ABCD|
|format|Format string|string.format("the value is:%d",4)|the value is:4|
|sub|Substring|string.sub("abcd",2)|bcd|
|||string.sub("abcd",-2)|cd|
|||string.sub("abcd",2,-2)|bc|
|||string.sub("abcd",2,3)|bc|
|find|Find substring (position)|string.find("cdcdcdcd","ab")|nil|
|||string.find("cdcdcdcd","cd")|1 2|
|||string.find("cdcdcdcd","cd",7)|7 8|
|match|Find substring (content)|string.match("cdcdcdcd","ab")|nil|
|||string.match("cdcdcdcd","cd")|cd|
|gsub|Substitute in string|string.gsub("abcdabcd","a","z")|zbcdzbcd 2|
|||string.gsub("aaaa","a","z",3)|zzza 3|
|byte|Char to integer|string.byte("ABCD",4)|68|
|char|Integers to chars|string.char(97,98,99,100)|abcd|

## Basic patterns

| Class | Description | Example | Result |
|------|----|----|----|
|.|Any char|string.find("",".")|nil|
|%s|Whitespace|string.find("ab cd","%s%s")|3 4|
|%S|Non-whitespace|string.find("ab cd","%S%S")|1 2|
|%p|Punctuation|string.find("ab,.cd","%p%p")|3 4|
|%P|Non-punctuation|string.find("ab,.cd","%P%P")|1 2|
|%c|Control char|string.find("abcd\t\n","%c%c")|5 6|
|%C|Non-control char|string.find("\t\nabcd","%C%C")|3 4|
|%d|Digit|string.find("abcd12","%d%d")|5 6|
|%D|Non-digit|string.find("12abcd","%D%D")|3 4|
|%x|Hex digit|string.find("efgh","%x%x")|1 2|
|%X|Non-hex digit|string.find("efgh","%X%X")|3 4|
|%a|Letter|string.find("AB12","%a%a")|1 2|
|%A|Non-letter|string.find("AB12","%A%A")|3 4|
|%l|Lowercase|string.find("ABab","%l%l")|3 4|
|%L|Uppercase|string.find("ABab","%L%L")|1 2|
|%u|Uppercase|string.find("ABab","%u%u")|1 2|
|%U|Non-uppercase|string.find("ABab","%U%U")|3 4|
|%w|Alnum|string.find("a1()","%w%w")|1 2|
|%W|Non-alnum|string.find("a1()","%W%W")|3 4|

## Escape character %

| Class | Description | Example | Result |
|------|----|----|----|
|%|Escape percent|string.find("abc%..","%%")|4 4|
|||string.find("abc..d","%.%.")|4 5|

## Character classes with []

| Class | Description | Example | Result |
|------|----|----|----|
|[01]|Binary digit|string.find("32123","[01]")|3 3|
|[AB][CD]|AC, AD, BC, BD|string.find("ABCDEF","[AB][CD]")|2 3|
|[\[\]]|A pair of []|string.find("ABC[]D","[\[\]]")|4 5|
|[1-3]|Digit 1-3|string.find("312","[1-3][1-3][1-3]")|1 3|
|[b-d]|Letter b-d|string.find("dbc","[b-d][b-d][b-d]")|1 3|
|[^%s]|Non-whitespace|string.find(" a ","[^%s]")|3 3|
|[^%d]|Non-digit|string.find("123a","[^%d]")|4 4|
|[^%a]|Non-letter|string.find("abc1","[^%a]")|4 4|

## Captures with ()

| Class | Description | Example | Result |
|------|----|----|----|
|()|Capture|string.find("12ab","(%a%a)")|3 4 ab|
|||string.find("ab12","(%d%d)")|3 4 12|

## Pattern modifiers

| Mod | Description | Example | Result |
|------|----|----|----|
|+|One or more (greedy)|string.find("aaabbb","(a+b)")|1 4 aaab|
|||string.find("cccbbb","(a+b)")|nil|
|-|Zero or more (non-greedy)|string.find("zzxyyy","(xy-)")|3 3 x|
|||string.find("zzzyyy","(x-y)")|4 4 y|
|*|Zero or more (greedy)|string.find("mmmnnn","(m*n)")|1 4 mmmn|
|||string.find("lllnnn","(m*n)")|4 4 n|
|?|Zero or one|string.find("aaabbb","(a?b)")|3 4 ab|
|||string.find("cccbbb","(a?b)")|4 4 b|

## Common uses of match

| Description | Example | Result |
|----|----|----|
|Match Chinese|string.match("男女abc123","([^%w%p]+)")|男女|
|Match letters|string.match("男女abc123","(%a+)")|abc|
|Match digits|string.match("男女abc123","(%d+)")|123|
|Match letters and digits|string.match("男女abc123","(%w+)")|abc123|

---

Source: [Generate a Random Number (sys.rnd)](https://xxtouch.app/en/docs/handbook/sys/sys.rnd.md)
Path: handbook/sys/sys.rnd.md

# Generate a Random Number (sys.rnd)

## Declaration

```lua
num = sys.rnd()
```

## Returns

- num
  Integer. In range 0~4294967295.

## Description

> Generates a true random number.

## Examples

```lua
math.randomseed(sys.rnd()) -- seed with a true random number
local r = math.random(1, 100)
```

---

Source: [! Millisecond delay (:msleep)](https://xxtouch.app/en/docs/handbook/touch/touchm_msleep.md)
Path: handbook/touch/touchm_msleep.md

# ! Millisecond delay (:msleep)

## Declaration

```lua
te = te:msleep(ms)
```

## Parameters

- ms
  Number, optional. Delay time in milliseconds. Default: 0.1.

## Returns

- te
  Touch event object itself. You can get a touch event object via [`touch.on`](/en/docs/handbook/touch/touch.on.md).

## Description

- Delay function. It does not change the object; it just blocks the current thread. Alias: `:delay`.
- This method may yield; other [threads](/en/docs/handbook/thread/index.md) may run before it returns.

## Example

```lua
-- Touch at 100,100, wait 300 ms, then lift
touch.on(100, 100):msleep(300):off()
```

---

Source: [Generate a Time-Based One-Time Password (utils.totp_next)](https://xxtouch.app/en/docs/handbook/utils/utils.totp_next.md)
Path: handbook/utils/utils.totp_next.md

# Generate a Time-Based One-Time Password (utils.totp_next)

## Declaration

```lua
code, err = utils.totp_next(timestamp, url[, secret])
```

## Parameters

- timestamp
  Integer. Unix timestamp in seconds. Pass -1 to use the current time.
- url
  String. TOTP URL in the `otpauth://totp/...` format.
- secret
  String. Base32 secret. Optional. When provided, this secret is used to generate the code.

## Returns

- code
  String. Generated one-time password.
- err
  String. Error message returned when generation fails.

## Description

> Available after 2026-01-07.
> Generate a time-based one-time password from a TOTP URL.
> The URL usually contains `secret`, and may also contain `digits`, `period`, and `algorithm`.
> `algorithm` can be `SHA1`, `SHA256`, or `SHA512`.

## Examples

```lua
local url = "otpauth://totp/Demo:alice?secret=JBSWY3DPEHPK3PXP&issuer=Demo&digits=6&period=30&algorithm=SHA1"

local code, err = utils.totp_next(-1, url)
if code then
    nLog(code)
else
    nLog(err)
end
```

---

Source: [Set a Control Value in the Config UI (xui.set)](https://xxtouch.app/en/docs/handbook/xui/xui.set.md)
Path: handbook/xui/xui.set.md

# Set a Control Value in the Config UI (xui.set)

## Declaration

```lua
ok = xui.set(domain, key, value)
```

## Parameters

- domain
  String. The defaults domain identifier used by the config UI.
- key
  String. The control's key identifier in the config UI.
- value
  Any. Different controls accept different value types.

## Returns

- ok
  Boolean. true on success; false on failure.

## Description

> If the config UI is currently displayed, this function immediately updates the displayed value.
> This function does not validate value types. If you need to ensure the saved value type is valid, call `xui.setup` after setting to validate/correct.
> See the config UI standard: [XUI](/XUI/README.md)

## Examples

```lua
xui.set('com.yourcompany.A-Script-Bundle', 'enabled', true)
xui.setup('interface.xui')
```

---

Source: [Check if app is running (app.is_running)](https://xxtouch.app/en/docs/handbook/app/app.is_running.md)
Path: handbook/app/app.is_running.md

# Check if app is running (app.is_running)

## Declaration

```lua
ok = app.is_running(bid)
```

## Parameters

- bid
  String. App bundle identifier. You can find it in `XXT App -> More -> App List`.

## Returns

- ok
  Boolean. Whether the app is running (foreground or background).

## Description

- To check if an app is in the foreground, compare with [`app.front_bid`](/en/docs/handbook/app/app.front_bid.md):
```lua
if "com.tencent.mqq" == app.front_bid() then
    sys.alert('QQ is in foreground')
end
```
Note: uses non-chapter API [`sys.alert`](/en/docs/handbook/sys/sys.alert.md).

## Example

```lua
if app.is_running("com.tencent.mqq") then
    sys.alert('QQ is running')
end
```
Note: uses non-chapter API [`sys.alert`](/en/docs/handbook/sys/sys.alert.md).

---

Source: [ML multi-array module](https://xxtouch.app/en/docs/handbook/coreml/coreml.multi_array_module.md)
Path: handbook/coreml/coreml.multi_array_module.md

# ML multi-array module

`MLMultiArray` is the most common tensor type in CoreML.
This page summarizes the `coreml` APIs related to `MLMultiArray`, including:

- creating tensors
- converting Lua / image / OpenCV data into tensors
- converting between `MLMultiArray` and ORT tensors
- common math, reductions, sorting, and concatenation
- detection / OBB / mask / keypoint / tracker post-processing helpers

If you want to wrap classifiers, embedding models, text models, detection models, or other general-purpose CoreML models in Lua, this page is the main foundation.

> **This module is available in versions released after 20260319**

## Creation and conversion

### `coreml.new_multi_array(opts)` / `coreml.tensor(opts)`

```lua
array, err = coreml.new_multi_array({
    shape = shape,
    data_type = data_type,
})
```

Creates an empty CoreML multi-array object that can later be used as model input or an intermediate tensor.

- `shape` is the target shape, for example `{1, 3, 224, 224}`
- `data_type` can be `"int32"`, `"float32"`, `"float16"`, or `"double"`; `"float64"` is accepted as an alias for `"double"`
- `coreml.tensor(opts)` is an equivalent alias

### `coreml.multi_array_from_table(data, opts)` / `coreml.tensor_from_table(data, opts)`

```lua
array, err = coreml.multi_array_from_table(data, {
    shape = shape,
    data_type = data_type,
})
```

Converts Lua table data explicitly into an `MLMultiArray`.

- `shape` must match the total number of elements
- `data_type` follows the same rules as `new_multi_array()`
- `coreml.tensor_from_table(...)` is an equivalent alias

### `coreml.tensor_from_image(image[, opts])`

```lua
array, meta = coreml.tensor_from_image(image, opts)
```

Converts an image object into a CoreML-ready tensor using explicit preprocessing options.

Common options:

- `width` / `height`
- `layout`: only `"nchw"` and `"nhwc"` are supported
- `channel_order`: `"rgb"`, `"bgr"`, `"gray"`, `"grey"`, or `"grayscale"`
- `data_type`
- `scale`
- `mean`
- `std`
- `resize_mode`: `"stretch"`, `"letterbox"`, `"center_crop"`
- `letterbox_mode`: supports `"center"` and `"top_left"`; `"topleft"` is treated as `"top_left"`
- `pad_color`
- `interpolation`: `"bilinear"`, `"nearest"`
- `alpha_mode`: `"ignore"`, `"white"`, `"black"`, `"premultiply"`
- `crop = {x, y, width, height}`

Notes:

- This function only performs explicitly configured image tensorization; it does not silently bind itself to one model's preprocessing rules
- On success, the second return value is a preprocessing metadata table; on failure, it returns `nil, err`
- Common metadata fields include:
  `src_width`, `src_height`, `crop_x`, `crop_y`, `crop_width`, `crop_height`, `dst_width`, `dst_height`, `resized_width`, `resized_height`, `scale_x`, `scale_y`, `ratio`, `pad_left`, `pad_top`, `pad_right`, `pad_bottom`, `resize_mode`, `offset_x`, `offset_y`, and `letterbox_mode`

### `coreml.tensor_from_images(images[, opts])`

```lua
batch_array, batch_meta = coreml.tensor_from_images({img1, img2}, {
    width = 640,
    height = 640,
    layout = "nchw",
})
```

Converts a batch of images into one `MLMultiArray`.

- Source image sizes may differ
- The batch can be formed as long as each image resolves to the same output shape and `data_type`
- The second return value is a metadata array aligned with the input order

### `coreml.image_from_tensor(tensor[, opts])`

```lua
image, err = coreml.image_from_tensor(tensor, opts)
```

Converts a 2D / 3D / 4D `MLMultiArray` back into an image object. Useful for debugging model inputs and outputs.

Common options:

- `layout`
- `channel_order`
- `batch_index`: **1-based**, default `1`
- `scale`
- `mean`
- `std`
- `clamp`
- `value_range`: `"0_255"` or `"0_1"`

Notes:

- Only 2D / 3D / 4D tensors are supported
- The channel count must be `1` or `3`

### `coreml.image_to_multi_array(image[, opts])`

This is the old API name. It is now only a compatibility alias of `coreml.tensor_from_image(...)`. New code should prefer `tensor_from_image()`.

### `coreml.tensor_from_cv_mat(mat[, opts])` / `coreml.multi_array_from_cv_mat(mat[, opts])`

Converts a `cv.mat` into an `MLMultiArray`.

- Requires `require("image.cv")`
- Both names are equivalent aliases

### `coreml.tensor_from_quad(mat, quad[, opts])` / `coreml.multi_array_from_quad(mat, quad[, opts])`

```lua
array, err = coreml.tensor_from_quad(mat, {
    {x = 0, y = 0},
    {x = 100, y = 0},
    {x = 100, y = 32},
    {x = 0, y = 32},
}, {
    width = 100,
    height = 32,
    layout = "hwc",
    channel_order = "rgb",
    data_type = "float32",
})
```

Runs a perspective crop from a `cv.mat` using a quadrilateral region and converts the result directly into an `MLMultiArray`.

- Requires `require("image.cv")`
- `quad` may be passed directly as four points, or as a table with a `points` field
- Common `opts` mostly match `tensor_from_image()`, with extra commonly used fields such as `content_width`, `content_height`, and `border_type`
- Useful for OCR rectification plus tensorization of a single text box

### `coreml.tensor_from_quads(mat, quads[, opts])` / `coreml.multi_array_from_quads(mat, quads[, opts])`

```lua
batch_array, err = coreml.tensor_from_quads(mat, {
    {
        points = quad1,
        content_width = 96,
        content_height = 32,
    },
    {
        points = quad2,
        content_width = 80,
        content_height = 32,
    },
}, {
    width = 96,
    height = 32,
    resize_mode = "top_left_letterbox",
    border_type = "replicate",
})
```

Runs perspective crops for multiple quadrilaterals and automatically packs the results into a batch tensor.

- Requires `require("image.cv")`
- `quads` must be a non-empty array; each item may include `points`
- Per-item `content_width` and `content_height` override the same global fields in `opts`
- The return value is packed with `stack()` or `concat()` depending on tensor rank, which is convenient for OCR batch preprocessing

### `coreml.multi_array_from_ort_tensor(tensor[, data_type])`

```lua
array, err = coreml.multi_array_from_ort_tensor(ort_tensor[, "float32"])
```

Copies an `onnxruntime.tensor` into an `MLMultiArray` using a native bridge.

- This function does not exist by default; it is injected into the built-in `coreml` module only after `require("onnxruntime")`
- The conversion is a native copy and does not go through a Lua table
- `string` tensors cannot be converted into `MLMultiArray`

## Type checks and aliases

### `coreml.is_multi_array(value)` / `coreml.is_tensor(value)`

```lua
is_multi_array = coreml.is_multi_array(value)
```

Checks whether a value is a `coreml_multi_array_object`. `is_tensor()` is an equivalent alias.

## Module-level helper functions

### Basic tensor helpers

- `coreml.concat(arrays, axis)`
- `coreml.stack(arrays, axis)`
- `coreml.gather(array, dim, indices)`
- `coreml.take(array, indices[, dim])`
- `coreml.gather_rows(array, indices)`
- `coreml.clamp(array, min, max)`
- `coreml.sigmoid(array)`
- `coreml.exp(array)`
- `coreml.where(condition, x, y)`
- `coreml.matmul(lhs, rhs)`

Notes:

- `take()` defaults to dimension `1`
- `gather_rows()` is a convenience alias for `take(array, indices, 1)`
- `where()` supports mixing scalars and `MLMultiArray` values and applies broadcasting rules
- `matmul()` currently supports rank-1 / rank-2 input combinations

### Geometry and detection helpers

- `coreml.nms(boxes, scores[, opts])`
- `coreml.box_points(rotated_boxes)`
- `coreml.xywh_to_xyxy(boxes)`
- `coreml.xyxy_to_xywh(boxes)`
- `coreml.rotated_iou(lhs, rhs)`
- `coreml.rotated_nms(boxes, scores[, opts])`

Notes:

- `nms()` expects `boxes` shaped `[N, 4]` and `scores` shaped `[N]` or `[N, C]`
- `rotated_nms()` expects `boxes` shaped `[N, 5]`; its `scores` argument is currently a Lua number array
- Both return an `MLMultiArray` of **1-based** kept indices

### Decode and record helpers

- `coreml.create_decoder(schema)`
- `coreml.decode_yolo(output[, opts])`
- `coreml.decode_yolo_obb(output[, opts])`
- `coreml.decode_matrix_candidates(output, schema[, opts])`
- `coreml.decode_dense_detection(output, opts)`
- `coreml.records_from_boxes(boxes, scores, class_ids[, keep_indices])`
- `coreml.obb_records_from_rows(rows, scores, class_ids[, angles[, keep_indices[, opts]]])`
- `coreml.points_to_records(points[, opts])`

Notes:

- `create_decoder()` returns a decoder object that supports `:decode()`, `:task()`, and `:schema()`
- `decode_dense_detection()` returns `{ boxes, scores, labels }`; when the input is batched, it returns a batch result array
- `decode_dense_detection()` requires `opts.strides`, and it must be a non-empty array of positive integers
- `decode_dense_detection()` also requires `decode_width` and `decode_height`, and currently supports only `box_encoding = "grid_center_log_wh"`
- `records_from_boxes()`, `obb_records_from_rows()`, and `points_to_records()` turn tensor outputs into record tables that are easier to consume from Lua

### Mask, keypoint, and tracking helpers

- `coreml.threshold_masks(masks, threshold)`
- `coreml.crop_masks_by_boxes(masks, boxes)`
- `coreml.resize_masks(masks, width, height[, opts])`
- `coreml.mask_iou(lhs_mask, rhs_mask)`
- `coreml.mask_to_polygon(mask[, opts])`
- `coreml.proto_masks(proto, coeffs, boxes, image_width, image_height[, opts])`
- `coreml.project_masks(proto, coeffs, boxes, image_width, image_height[, opts])`
- `coreml.db_postprocess(score_map[, opts])`
- `coreml.tracker([opts])`
- `coreml.reshape_keypoints(points[, keypoint_count[, keypoint_dim|opts]])`
- `coreml.scale_boxes(boxes, transform)`
- `coreml.clip_boxes(boxes, clip_width, clip_height)`
- `coreml.scale_points(points, transform[, opts])`
- `coreml.scale_keypoints(points, transform[, opts])`
- `coreml.clip_keypoints(points, clip_width, clip_height[, opts])`
- `coreml.ctc_greedy_decode(logits[, opts])`
- `coreml.sample_logits(logits[, opts])`

Notes:

- `project_masks()` is an alias of `proto_masks()`
- `mask_iou()` computes the intersection-over-union between two masks directly
- `mask_iou()` also accepts a third `opts` argument with `compare_size = true`, or explicit `width` / `height` for the comparison size
- `db_postprocess()` is intended for DB / DBNet-style text-detection post-processing; inputs may be `[H, W]`, `[C, H, W]`, or `[N, C, H, W]`
- `db_postprocess()` returns a detection array where each item contains `score`, `points`, and `box`; `meta` / `image_meta` can reuse preprocessing metadata returned by image tensorization
- `tracker()` returns a tracker object that supports `:update()`, `:reset()`, `:state()`, and `:close()`
- `ctc_greedy_decode()` accepts `[T, C]` or `[N, T, C]` logits
- `ctc_greedy_decode()` supports `blank_index`, `merge_repeated`, `apply_softmax`, `return_probabilities`, and `charset`
- `ctc_greedy_decode()` always returns `indices`; `text` appears only when `charset` is provided; `confidence` appears only when `apply_softmax` or `return_probabilities` is enabled; `probabilities` and `probability_confidence` appear only when `return_probabilities` is enabled
- `sample_logits()` supports `argmax`, `temperature`, `top_k`, `top_p`, `min_p`, and `seed`
- `sample_logits()` returns a single **1-based** index for 1D logits; for batched logits it returns an index `MLMultiArray`

## Basic object methods

### Basic queries

- `array:shape()`
- `array:data_type()`
- `array:count()`
- `array:strides()`
- `array:to_table()`
- `array:to_cv_mat([opts])`

Notes:

- `data_type()` returns `"int32"`, `"float32"`, `"float16"`, or `"double"`
- `to_cv_mat()` requires `require("image.cv")`

### ORT bridge

- `array:to_ort_tensor([data_type])`

This method does not exist by default; it is injected into `coreml_multi_array_object` only after `require("onnxruntime")`.

## Type and shape transforms

- `array:astype(data_type)`
- `array:clone()`
- `array:reshape(shape)`
- `array:transpose(axes)`
- `array:slice(dim, start, stop[, step])`
- `array:select(dim, index)`
- `array:squeeze([dim])`
- `array:unsqueeze(dim)`
- `array:flatten([start_dim[, end_dim]])`

Notes:

- `reshape()`, `transpose()`, `squeeze()`, `unsqueeze()`, and `flatten()` return views by default and do not copy underlying data
- `reshape()` / `flatten()` fail on non-contiguous layouts; call `clone()` first if needed
- `slice()` and `select()` return new contiguous tensors, not views
- The indexing semantics of `slice()` / `select()` / `gather()` / `take()` stay **1-based** to match the ONNX docs

## Numeric and indexing methods

- `array:gather(dim, indices)`
- `array:take(indices[, dim])`
- `array:l2_norm()`
- `array:dot(other)`
- `array:max([axis])`
- `array:min([axis])`
- `array:add(other)`
- `array:sub(other)`
- `array:mul(other)`
- `array:div(other)`
- `array:clamp(min, max)`
- `array:sigmoid()`
- `array:exp()`
- `array:matmul(other)`
- `array:scale(number)`

Notes:

- `add/sub/mul/div` support scalars and limited broadcasting
- `sigmoid()`, `exp()`, and `matmul()` promote results to floating-point output

## Reductions, ranking, and selection

- `array:sum([axis])`
- `array:mean([axis])`
- `array:softmax([axis])`
- `array:normalize([axis])`
- `array:argmax([axis])`
- `array:topk(k[, axis])`
- `array:sort([axis[, descending]])`

Notes:

- `argmax()` without an axis returns the **1-based** linear index of the maximum value in the whole array
- `argmax(axis)` returns an `MLMultiArray` of indices
- `topk()` returns `{ values = tensor, indices = tensor }`
- `sort()` returns a new sorted `MLMultiArray`; it does **not** return a separate index table

## Geometry and post-processing object methods

- `array:clip_boxes(clip_width, clip_height)`
- `array:xywh_to_xyxy()`
- `array:xyxy_to_xywh()`
- `array:reshape_keypoints([keypoint_count[, keypoint_dim|opts]])`
- `array:scale_points(transform[, opts])`
- `array:clip_keypoints(clip_width, clip_height[, opts])`

These methods share the same underlying implementation as the module-level helpers; they simply pass the current array as the first argument.

## Usage notes

- In the newer general-purpose CoreML APIs, `MLMultiArray` is the default first-class data type; avoid converting to Lua tables prematurely
- Most bulk operations should stay on tensor objects; use `to_table()` mainly for debugging, small outputs, or legacy code compatibility
- Image preprocessing should be configured explicitly through `tensor_from_image()` options rather than baking one model's preprocessing into a generic pipeline
- If you need an isolated copy, or want to turn a non-contiguous layout into a contiguous tensor, call `clone()` explicitly

## Example

```lua
local arr = assert(coreml.tensor({
    shape = {2, 3},
    data_type = "float32",
}))

local filled = assert(coreml.tensor_from_table({
    {1, 2, 3},
    {4, 5, 6},
}, {
    shape = {2, 3},
    data_type = "float32",
}))

local merged = assert(coreml.concat({filled, filled}, 1))
print(coreml.is_tensor(merged))
print(merged:shape())
```

---

Source: [Vibrate Device (device.vibrator)](https://xxtouch.app/en/docs/handbook/device/device.vibrator.md)
Path: handbook/device/device.vibrator.md

# Vibrate Device (device.vibrator)

## Declaration

```lua
device.vibrator()
```

## Description

> Trigger a short vibration. Devices without a vibration motor will not vibrate.

## Example

```lua
device.vibrator()
```

---

Source: [Add a text input (:add_input)](https://xxtouch.app/en/docs/handbook/dialog/dialogm_add_input.md)
Path: handbook/dialog/dialogm_add_input.md

# Add a text input (:add_input)

## Declaration

```lua
dialog_obj = dialog_obj:add_input(label [, default_value])
```

## Parameters

- label
  String. The label text shown on the left of the input
- default_value
  String or Number. Default value in the input box

## Returns

- dialog_obj
  Dialog. Returns the dialog itself
- :show() return type
  String. The entered text

## Description

> Add a text input to the dialog

## Example

```lua
local c, s = dialog():add_input('An input', 'default'):show()
sys.alert('Entered: ' .. s['An input'])
```
Note: Uses function outside this chapter [`sys.alert`](/en/docs/handbook/sys/sys.alert.md)

## Full example

See [:show()](/en/docs/handbook/dialog/dialogm_show.md)

---

Source: [Set a specific line in a text file (file.set_line)](https://xxtouch.app/en/docs/handbook/file/file.set_line.md)
Path: handbook/file/file.set_line.md

# Set a specific line in a text file (file.set_line)

## Declaration

```lua
ok, err = file.set_line(path, n, content)
```

## Parameters

- path
  String. Absolute file path.
- n
  Integer. Line number. 0 means last line + 1. Negative means counting from the end.
- content
  String. Data to set to the specified line.

## Returns

- ok
  Boolean. true if success, false if failure.
- err
  String. Error message when operation fails.

## Description

> Set the content of a specific line. If the number of lines is not enough, empty lines will be filled. Creates file if it does not exist. Returns false if directory does not exist.
> This function automatically strips UTF-8 BOM at the file head.

## Example

```lua
local success, err = file.set_line("/var/mobile/1.txt", 3, "Third line content")
if success then
    sys.alert("Success")
else
    sys.alert("Failed: "..err)
end
```
**Note**: Uses [`sys.alert`](/en/docs/handbook/sys/sys.alert.md)

---

Source: [Get gamepad device properties (:get_properties)](https://xxtouch.app/en/docs/handbook/gamepad/gamepadm_get_properties.md)
Path: handbook/gamepad/gamepadm_get_properties.md

# Get gamepad device properties (:get_properties)

> **This method is available in versions after 20260805**

## Declaration

```lua
properties = pad:get_properties()
```

## Returns

- properties
  Table. A copy of the configuration properties saved when the device was created

## Description

- This returns the configuration saved when the gamepad was created, which may include system-managed properties
- The return value does not represent the values ultimately used by the system. Do not use it to determine whether the target app recognized the gamepad
- Scripts should rely only on fields they supplied or that are documented

## Example

```lua
local pad = assert(gamepad.connect())

local properties = pad:get_properties()
print(properties.Product)
print(properties.Transport)
assert(pad:disconnect())
```

---

Source: [Save image to Photos (:save_to_album)](https://xxtouch.app/en/docs/handbook/image/imagem_save_to_album.md)
Path: handbook/image/imagem_save_to_album.md

# Save image to Photos (:save_to_album)

## Declaration

```lua
img:save_to_album()
```

## Description

> Export the image to the system Photos app

## Example 1

```lua
-- Download a small image from the web and save it to Photos
local c, h, r = http.get("https://www.xxtouch.app/img/Logo.png", 10)
if (c == 200) then
    local img = image.load_data(r)
    img:save_to_album()
    sys.alert("Image saved to Photos")
else
    sys.alert("Download failed")
end
```
Note: This example uses functions outside this chapter [`sys.alert`](/en/docs/handbook/sys/sys.alert.md), [`http.get`](/en/docs/handbook/http/http.get.md)

## Example 2

```lua
-- Capture full screen and save to Photos
screen.image():save_to_album()
```
Note: This example uses a function outside this chapter [`screen.image`](/en/docs/handbook/screen/screen.image.md)

## Example 3

```lua
-- Save a file to Photos (example only; add existence checks before saving)
image.load_file("/var/mobile/1.png"):save_to_album()
```

## Example 4

```lua
-- Save a file to Photos with type checks
img = image.load_file("/var/mobile/1.png")
if image.is(img) then
    img:save_to_album()
end
```

---

Source: [Disconnect the global hardware keyboard (key.disconnect_global_keyboard)](https://xxtouch.app/en/docs/handbook/key/key.disconnect_global_keyboard.md)
Path: handbook/key/key.disconnect_global_keyboard.md

# Disconnect the global hardware keyboard (key.disconnect_global_keyboard)

> **This function is available in versions after 20260805**

## Declaration

```lua
success, err = key.disconnect_global_keyboard()
```

## Returns

- success
  Boolean. Returns `true` after disconnection or when no global hardware keyboard is connected, and `false` on failure.
- err
  String. Error message returned when disconnection fails.

## Description

> Releases all keys and disconnects the current global hardware keyboard. The existing key APIs resume their previous behavior afterwards.

- This function may be called repeatedly. It also returns success when no global hardware keyboard is connected.
- If the global hardware keyboard is running a `:press` or `:send_text` sequence, disconnection returns `false, "hardware keyboard is busy"`.
- Keys already held by `key.down` are released during disconnection. A later matching `key.up` does not send the input again.

## Example

```lua
local success, err = key.disconnect_global_keyboard()
assert(success, err)
```

---

Source: [Disconnect the hardware mouse (:disconnect)](https://xxtouch.app/en/docs/handbook/mouse/mousem_disconnect.md)
Path: handbook/mouse/mousem_disconnect.md

# Disconnect the hardware mouse (:disconnect)

> **This method is available in versions after 20260805**


## Declaration

```lua
success, error_message = mouse_obj:disconnect()
```


## Returns

- success
  Boolean. `true` if disconnection succeeds; otherwise `false`.
- error_message
  String. The reason disconnection failed.


## Description

> Releases all mouse buttons and disconnects the object. This method may be called repeatedly.
> XXTouch automatically releases all mouse buttons on explicit disconnection, Lua garbage collection, or script termination.
> Even if releasing the buttons fails, the object still disconnects and the operation is not retried as a touch event.


## Example

```lua
local m = assert(mouse.connect())
local ok, err = m:disconnect()
assert(ok, err)
```

---

Source: [lua-openssl](https://xxtouch.app/en/docs/handbook/open-source/lua-openssl.md)
Path: handbook/open-source/lua-openssl.md

# lua-openssl

[lua-openssl manual](https://zhaozg.github.io/lua-openssl/index.html)

[lua-openssl GitHub repository](https://github.com/zhaozg/lua-openssl)

---

XXTouch includes [zhaozg/lua-openssl](https://github.com/zhaozg/lua-openssl), which can be used directly with `require("openssl")`.

```lua
local openssl = require("openssl")
```

## AES-128-ECB Example

```lua
local cipher = require("openssl").cipher

local key = "1234567890abcdef" -- AES-128 requires a 16-byte key
local plaintext = "hello xxtouch"

local encrypted = assert(cipher.encrypt("aes-128-ecb", plaintext, key))
local decrypted = assert(cipher.decrypt("aes-128-ecb", encrypted, key))

assert(decrypted == plaintext)
```

## AES-128-CBC Example

```lua
local cipher = require("openssl").cipher

local key = "1234567890abcdef" -- AES-128 requires a 16-byte key
local iv = "abcdef1234567890"  -- AES-128-CBC requires a 16-byte IV
local plaintext = "hello xxtouch"

local encrypted = assert(cipher.encrypt("aes-128-cbc", plaintext, key, iv))
local decrypted = assert(cipher.decrypt("aes-128-cbc", encrypted, key, iv))

assert(decrypted == plaintext)
```

## AES-128-GCM Example

```lua
local openssl = require("openssl")
local cipher = openssl.cipher

local evp = assert(cipher.get("aes-128-gcm"))
local key = openssl.random(16)
local iv = openssl.random(12)
local aad = "xxtouch"
local plaintext = "hello xxtouch"
local tag_len = 16

local enc = assert(evp:encrypt_new())
assert(enc:ctrl(cipher.EVP_CTRL_GCM_SET_IVLEN, #iv))
assert(enc:init(key, iv))
assert(enc:update(aad, true))
local encrypted = assert(enc:update(plaintext))..assert(enc:final())
local tag = assert(enc:ctrl(cipher.EVP_CTRL_GCM_GET_TAG, tag_len))

local dec = assert(evp:decrypt_new())
assert(dec:ctrl(cipher.EVP_CTRL_GCM_SET_IVLEN, #iv))
assert(dec:init(key, iv))
assert(dec:update(aad, true))
local decrypted = assert(dec:update(encrypted))
assert(dec:ctrl(cipher.EVP_CTRL_GCM_SET_TAG, tag))
decrypted = decrypted..assert(dec:final())

assert(decrypted == plaintext)
```

---

Source: [Push to back of process queue (proc_queue_push_back)](https://xxtouch.app/en/docs/handbook/proc/proc_queue_push_back.md)
Path: handbook/proc/proc_queue_push_back.md

# Push to back of process queue (proc_queue_push_back)

## Declaration

```lua
size = proc_queue_push_back(key, value)
```

## Parameters

- key
  String.
- value
  String. The value to push.

## Returns

- size
  Integer. Size after pushing. If 0, push failed.

## Description

- This function is equivalent to [`proc_queue_push`](/en/docs/handbook/proc/proc_queue_push.md).
- All process queues whose names start with "xxtouch." or "1ferver." are reserved.
- Queue size must not exceed 10000; exceeding values will drop earliest entries.
- Push a value to the back and return the size.
- Empty string cannot be pushed.

## Example

```lua
local size = proc_queue_push_back("billnos", "name")
if size ~= 0 then
    print("has "..size.." bill(s)")
else
    print("failed")
end
```

---

Source: [Find Color - Color Offset Mode (screen.find_color)](https://xxtouch.app/en/docs/handbook/screen/screen.find_color-co.md)
Path: handbook/screen/screen.find_color-co.md

# Find Color - Color Offset Mode (screen.find_color)

## Declaration

```lua
x, y = screen.find_color({
    [find_all = boolean,]
    [max_results = integer_value,]
    [max_miss = integer_value,]
    {x0, y0, {color0[, offset0]}},
    {dx*, dy*, {color*[, offset*]}},
    {dx*, dy*, {color*[, offset*]}},
    ...
}[, left, top, right, bottom ])
```

## Parameters

- find_all
  Boolean, optional. When true, returns a table of all match positions within the region, format `{{x1, y1}, {x2, y2}, ...}`. Default false.
- max_results
  Integer, optional. The maximum number of results when `find_all` is true. Up to 1000, default 100.
- max_miss
  Integer, optional. Maximum number of non-matching points allowed. Default 0 (all points must match).
- x0, y0
  Integer. Starting anchor coordinate. This establishes a reference point for calculating offset positions, not a search boundary. If unsure, use 0, 0.
- color0
  Integer. Color to match at the starting point.
- offset0
  Integer. Max color offset (or bias). A value greater than `0xff000000` activates inverse matching (matches colors that do NOT match the specified value).
- dx*, dy*
  Integer. Offset coordinate relative to the starting point.
- color*
  Integer. Expected color at the offset point.
- offset*
  Integer. Max color offset (or bias) at the offset point. A value greater than `0xff000000` activates inverse matching.
- left, top, right, bottom
  Integer, optional. Search region. Default is full screen.

## Returns

- x, y
  Integer. The coordinate of the first matched multi-point structure. Returns -1, -1 on failure.

## Description

> Find the position of the first fully matched multi-point color structure using color-offset mode.
> Coordinate parameters and return values follow the coordinate system initialized via [`screen.init`](/en/docs/handbook/screen/screen.init.md).
>
> Color offset (bias) represents a range of acceptable colors. For color `0x456789` with offset `0x123456`, the ranges are:
> Red: `0x45 ± 0x12`, Green: `0x67 ± 0x34`, Blue: `0x89 ± 0x56`.
>
> Use `0x` prefix for hex numbers.

## Example

```lua
x, y = screen.find_color({
    {  0,   0, {0xec1c23, 0x000000}},
    { 12,  -3, {0xffffff, 0x101010}},
    {  5, -18, {0x00adee, 0x123456}},
    { -1, -10, {0xffc823, 0x101001}},
    {  2, -34, {0xa78217, 0x101001}},
    { 12, -55, {0xd0d2d2, 0x101001}},
}, 0, 0, 100, 100)
--
-- Equivalent form with absolute coords:
--
x, y = screen.find_color({
    { 509, 488, {0xec1c23, 0x000000}},
    { 521, 485, {0xffffff, 0x101010}},
    { 514, 470, {0x00adee, 0x123456}},
    { 508, 478, {0xffc823, 0x101001}},
    { 511, 454, {0xa78217, 0x101001}},
    { 521, 433, {0xd0d2d2, 0x101001}},
}, 0, 0, 100, 100)
--
-- One-line compact form:
--
x, y = screen.find_color({ {0,0,{0xec1c23,0x000000} },{12,-3, {0xffffff,0x101010} },{5,-18, {0x00adee,0x123456} },{-1,-10,{0xffc823,0x101001} },{2,-34,{0xa78217,0x101001} },{12,-55,{0xd0d2d2,0x101001} }, },0,0,100,100)
--
-- Inverse matching demo (run on iPhone 5C home screen for results):
x, y = screen.find_color({
    { 516,  288, {0xffffff, 0x101010} },
    { 519,  286, {0xffffff, 0x101010} },
    { 521,  289, {0xffffff, 0x101010} },
    { 516,  296, {0xffffff, 0x101010} },
    { 522,  297, {0xffffff, 0x101010} },
    { 520,  295, {0xffffff, 0xff101010} },
    { 515,  291, {0xffffff, 0xff101010} },
    { 518,  284, {0xffffff, 0xff101010} },
    { 523,  298, {0xffffff, 0xff101010} },
    { 514,  298, {0xffffff, 0xff101010} },
    { 514,  296, {0xffffff, 0xff101010} },
})
--
-- Find-all demo (returns all positions):
results = screen.find_color({
    {  527,  278, {0xde1d26, 0x101010} },
    {  524,  285, {0x007aff, 0x101010} },
    {  555,  292, {0xe4ddc9, 0x101010} },
    {  536,  314, {0xffde02, 0x101010} },
    {  502,  291, {0xffde02, 0x101010} },
    {  502,  283, {0xe4ddc9, 0x101010} },
    find_all = true,
})
```

---

Source: [Applications of the math Library](https://xxtouch.app/en/docs/handbook/supplement/math-samples.md)
Path: handbook/supplement/math-samples.md

# Applications of the math Library

| Function | Description | Example | Result |
|------|----|----|----|
|pi|Pi|math.pi|3.1415926535898|
|abs|Absolute value|math.abs(-2012)|2012|
|ceil|Round up|math.ceil(9.1)|10|
|floor|Round down|math.floor(9.9)|9|
|max|Maximum of args|math.max(2,4,6,8)|8|
|min|Minimum of args|math.min(2,4,6,8)|2|
|x^y|x to the y power (Lua 5.3 removed `math.pow`; use the `^` operator instead)|2^16|65536.0|
|sqrt|Square root|math.sqrt(65536)|256.0|
|modf|Integer and fraction parts|math.modf(20.12)|20 0.12|
|randomseed|Set random seed|math.randomseed(os.time())||
|random|Random number|math.random(5,90)|5~90|
|rad|Degrees to radians|math.rad(180)|3.1415926535898|
|deg|Radians to degrees|math.deg(math.pi)|180.0|
|exp|e to the x|math.exp(4)|54.598150033144|
|log|Natural log of x|math.log(54.598150033144)|4.0|
|log (with base)|Log with given base (Lua 5.3 removed `math.log10`; use `math.log(x, 10)` instead)|math.log(1000, 10)|3.0|
|frexp|Decompose to x * (2 ^ y)|math.frexp(160)|0.625 8|
|ldexp|Compute x * (2 ^ y)|math.ldexp(0.625,8)|160.0|
|sin|Sine|math.sin(math.rad(30))|0.5|
|cos|Cosine|math.cos(math.rad(60))|0.5|
|tan|Tangent|math.tan(math.rad(45))|1.0|
|asin|Arcsine|math.deg(math.asin(0.5))|30.0|
|acos|Arccosine|math.deg(math.acos(0.5))|60.0|
|atan|Arctangent|math.deg(math.atan(1))|45.0|

---

Source: [Get Current Memory Info (sys.memory_info)](https://xxtouch.app/en/docs/handbook/sys/sys.memory_info.md)
Path: handbook/sys/sys.memory_info.md

# Get Current Memory Info (sys.memory_info)

## Declaration

```lua
info = sys.memory_info()
```

## Returns

- info
  Table. Key-value pairs describing current memory state.

## Examples

```lua
sys.alert(table.deep_dump(sys.memory_info()))
```
Note: uses [`table.deep_dump`](/en/docs/handbook/ext-table/table.deep_dump.md).

---

Source: [Generate a One-Time Password by Counter (utils.hotp_counter)](https://xxtouch.app/en/docs/handbook/utils/utils.hotp_counter.md)
Path: handbook/utils/utils.hotp_counter.md

# Generate a One-Time Password by Counter (utils.hotp_counter)

## Declaration

```lua
code, err = utils.hotp_counter(counter, url[, secret])
```

## Parameters

- counter
  Integer. Counter used to generate the HOTP code.
- url
  String. HOTP URL in the `otpauth://hotp/...` format.
- secret
  String. Base32 secret. Optional. When provided, this secret is used to generate the code.

## Returns

- code
  String. Generated one-time password.
- err
  String. Error message returned when generation fails.

## Description

> Available after 2026-01-07.
> Generate a one-time password from the specified counter and HOTP URL.
> The URL usually contains `secret`, and may also contain `digits` and `algorithm`.
> `algorithm` can be `SHA1`, `SHA256`, or `SHA512`.

## Examples

```lua
local url = "otpauth://hotp/Demo:alice?secret=JBSWY3DPEHPK3PXP&issuer=Demo&digits=6&algorithm=SHA1"

local code, err = utils.hotp_counter(1, url)
if code then
    nLog(code)
else
    nLog(err)
end
```

---

Source: [Read All Settings from a Domain (xui.read)](https://xxtouch.app/en/docs/handbook/xui/xui.read.md)
Path: handbook/xui/xui.read.md

# Read All Settings from a Domain (xui.read)

## Declaration

```lua
settings = xui.read(domain)
```

## Parameters

- domain
  String. The defaults domain identifier used by the config UI.

## Returns

- settings
  Table. All key-value pairs under the specified domain. Returns an empty table if the domain does not exist.

## Description

> Use this function to read multiple settings at once in one call.
> It does not validate value types. If you need to ensure value types are valid, call `xui.setup` first to validate/correct, then read.
> See the config UI standard: [XUI](/XUI/README.md)

## Examples

```lua
xui.setup('interface.xui')
local dict = xui.read('com.yourcompany.A-Script-Bundle')
local enabled = dict['enabled']
```

---

Source: [Get localized name by bundle ID (app.localized_name)](https://xxtouch.app/en/docs/handbook/app/app.localized_name.md)
Path: handbook/app/app.localized_name.md

# Get localized name by bundle ID (app.localized_name)

## Declaration

```lua
name = app.localized_name(bid)
```

## Parameters

- bid
  String. App bundle identifier. You can find it in `XXT App -> More -> App List`.

## Returns

- name
  String | nil. Localized name of the app, or nil if the app does not exist.

## Example

```lua
local name = app.localized_name("com.tencent.xin")
sys.alert(name) -- shows "WeChat" (the localized display name)
```
Note: uses non-chapter API [`sys.alert`](/en/docs/handbook/sys/sys.alert.md).

---

Source: [Play sound in background (device.play_sound)](https://xxtouch.app/en/docs/handbook/device/device.play_sound.md)
Path: handbook/device/device.play_sound.md

# Play sound in background (device.play_sound)

## Declaration

```lua
device.play_sound(path)
```

## Parameters

- path
  String. Absolute path to audio file. Supports mp3, wav, aac

## Description

> Play audio in the background
> This function does not block script execution. Audio playback stops when the script ends. If you need full playback, add a delay before exiting.

## Example

```lua
device.play_sound("/var/mobile/ten-years.mp3")
sys.msleep(205 * 1000) -- wait 205 seconds (3m25s)
```
Note: Uses function outside this chapter [`sys.msleep`](/en/docs/handbook/sys/sys.msleep.md)

---

Source: [Add an image (:add_image)](https://xxtouch.app/en/docs/handbook/dialog/dialogm_add_image.md)
Path: handbook/dialog/dialogm_add_image.md

# Add an image (:add_image)

## Declaration

```lua
dialog_obj = dialog_obj:add_image(image)
```

## Parameters

- image
  Image object to be added to the dialog

## Returns

- dialog_obj
  Dialog. Returns the dialog itself

## Description

> Add an image to the dialog

## Example

```lua
dialog():add_image(screen.image()):show() -- show a screenshot
```
Note: Uses function outside this chapter [`screen.image`](/en/docs/handbook/screen/screen.image.md)

## Full example

See [:show()](/en/docs/handbook/dialog/dialogm_show.md)

---

Source: [Convert to hex string (string.to_hex)](https://xxtouch.app/en/docs/handbook/ext-string/string.to_hex.md)
Path: handbook/ext-string/string.to_hex.md

# Convert to hex string (string.to_hex)

## Declaration

```lua
hex_text = string.to_hex(data[, prefix, suffix])
```

## Parameters

- data
  string. The string (or binary data) to convert to hex text.
- prefix
  string, optional. Prefix for each converted byte. Default: "".
- suffix
  string, optional. Suffix for each converted byte. Default: "".

## Returns

- hex_text
  string. The hex-encoded text.

## Description

> Convert a string (or binary data) to printable hex text.
> Keywords: image hex, hex image, file hex, hex file, data hex, hex data

## Example

```lua
-- Example 1:
sys.alert(string.to_hex('some data'))
-- "736f6d652064617461"
--
-- Example 2:
sys.alert((string.to_hex('some data'):gsub('(..)', '\\x%1')))
-- "\x73\x6f\x6d\x65\x20\x64\x61\x74\x61"
```
Note: Uses function outside of this chapter: [`sys.alert`](/en/docs/handbook/sys/sys.alert.md)

## More examples

[At the end of this chapter](/en/docs/handbook/ext-string/samples.md)

---

Source: [Insert content before a specific line (file.insert_line)](https://xxtouch.app/en/docs/handbook/file/file.insert_line.md)
Path: handbook/file/file.insert_line.md

# Insert content before a specific line (file.insert_line)

## Declaration

```lua
ok, err = file.insert_line(path, n, content)
```

## Parameters

- path
  String. Absolute file path.
- n
  Integer. Line number. 0 means last line + 1. Negative means counting from the end.
- content
  String. Data to insert before the specified line.

## Returns

- ok
  Boolean. true if success, false if failure.
- err
  String. Error message when operation fails.

## Description

> Insert content before the specified line. If the number of lines is not enough, empty lines will be filled. Creates file if it does not exist. Returns false if directory does not exist.
> This function automatically strips UTF-8 BOM at the file head.

## Example

```lua
local success, err = file.insert_line("/var/mobile/1.txt", 2, "Inserted line")
if success then
    sys.alert("Success")
else
    sys.alert("Failed: "..err)
end
```
**Note**: Uses [`sys.alert`](/en/docs/handbook/sys/sys.alert.md)

---

Source: [Disconnect a hardware gamepad (:disconnect)](https://xxtouch.app/en/docs/handbook/gamepad/gamepadm_disconnect.md)
Path: handbook/gamepad/gamepadm_disconnect.md

# Disconnect a hardware gamepad (:disconnect)

> **This method is available in versions after 20260805**

## Declaration

```lua
success, err = pad:disconnect()
```

## Returns

- success
  Boolean. True if the gamepad was disconnected; false on failure
- err
  String. Error message when the operation fails

## Description

- `disconnect` may be called repeatedly
- On explicit disconnection, Lua garbage collection, or script termination, all buttons are released, the analog sticks and directional pad are centered, and then the gamepad disconnects
- If input delivery fails, the gamepad resets and disconnects
- A failed gamepad operation is not retried through keyboard, touch, or another input method

## Example

```lua
local pad = assert(gamepad.connect())

local success, err = pad:disconnect()
assert(success, err)
```

---

Source: [Save image as a PNG file (:save_to_png_file)](https://xxtouch.app/en/docs/handbook/image/imagem_save_to_png_file.md)
Path: handbook/image/imagem_save_to_png_file.md

# Save image as a PNG file (:save_to_png_file)

## Declaration

```lua
img:save_to_png_file(path)
```

## Parameters

- path
  String. Absolute path to save the PNG file

## Description

> Save the image object to a PNG file. The file extension does not need to be .png

## Example

```lua
-- Capture full screen and save to file
screen.image():save_to_png_file("/var/mobile/1.png")
```
Note: This example uses a function outside this chapter [`screen.image`](/en/docs/handbook/screen/screen.image.md)

---

Source: [Hold down a hardware keyboard key (:down)](https://xxtouch.app/en/docs/handbook/key/hardware_keyboardm_down.md)
Path: handbook/key/hardware_keyboardm_down.md

# Hold down a hardware keyboard key (:down)

> **This method is available in versions after 20260805**

## Declaration

```lua
success, err = keyboard:down(key)
success, err = keyboard:down(usage_page, usage_id)
```

## Parameters

- key
  String. Uses the same key-name mapping as [`key.press`](/en/docs/handbook/key/key.press.md).
- usage_page
  Integer. Hardware keyboard objects currently accept only Keyboard/Keypad Usage Page `0x07`.
- usage_id
  Integer. Physical key identifier, not a character encoding.

## Returns

- success
  Boolean. Returns `true` when the key is held successfully and `false` on failure.
- err
  String. Error message returned when sending fails.

## Description

> Hold down a hardware keyboard key. Call the corresponding [`:up`](hardware_keyboardm_up.md) afterwards to release it.

- If the same keyboard is running a `:press` or `:send_text` sequence, this method returns `false, "hardware keyboard is busy"`.
- At most six non-modifier keys can be held at once; modifier keys do not count toward this limit.
- On failure, the method returns `false` and an error message. It is not retried through another input method.

## Example

```lua
local keyboard = assert(key.connect_keyboard())

assert(keyboard:press(0x07, 4))       -- Keyboard A
assert(keyboard:down(0x07, 0xE1))    -- Left Shift
assert(keyboard:up(0x07, 0xE1))

assert(keyboard:disconnect())
```

---

Source: [Pop from front of process queue (proc_queue_pop_front)](https://xxtouch.app/en/docs/handbook/proc/proc_queue_pop_front.md)
Path: handbook/proc/proc_queue_pop_front.md

# Pop from front of process queue (proc_queue_pop_front)

## Declaration

```lua
value = proc_queue_pop_front(key)
```

## Parameters

- key
  String.

## Returns

- value
  String. The popped value. If the queue does not exist or is empty, returns empty string.

## Description

- This function is equivalent to [`proc_queue_pop`](/en/docs/handbook/proc/proc_queue_pop.md).
- All process queues whose names start with "xxtouch." or "1ferver." are reserved.
- Pop a value from the front.

## Example

```lua
local billno = proc_queue_pop_front("billnos")
if billno ~= "" then
    print(billno)
else
    print("no bill")
end
```

---

Source: [Capture Screen Image (screen.image)](https://xxtouch.app/en/docs/handbook/screen/screen.image.md)
Path: handbook/screen/screen.image.md

# Capture Screen Image (screen.image)

## Declaration

```lua
img = screen.image([ left, top, right, bottom ])
```

## Parameters

- left, top, right, bottom
  Integer, optional. Image region. Default is full screen.

## Returns

- img
  Image object. See [Image module (image)](/en/docs/handbook/image/index.md).

## Description

> Capture the image of the full screen or a region.
> Coordinate parameters follow the coordinate system initialized via [`screen.init`](/en/docs/handbook/screen/screen.init.md).
> This method creates a new image object. For frequent usage, consider calling `image:destroy` to release memory in time: see [image:destroy](/en/docs/handbook/image/imagem_destroy.md).

## Example

```lua
-- Examples of screen.image
--
screen.image():save_to_album() -- Full-screen screenshot to album
--
screen.image():save_to_png_file("/var/mobile/1.png") -- Full-screen screenshot to file
--
screen.image(100, 100, 200, 200):save_to_album() -- Capture region and save to album
--
pasteboard.write(screen.image(100, 100, 200, 200):png_data(), "public.png")
-- Write captured region into pasteboard as PNG
```
**Note**: Uses [`:save_to_album`](/en/docs/handbook/image/imagem_save_to_album.md), [`:save_to_png_file`](/en/docs/handbook/image/imagem_save_to_png_file.md), [`:png_data`](/en/docs/handbook/image/imagem_png_data.md), [`pasteboard.write`](/en/docs/handbook/pasteboard/pasteboard.write.md)

---

Source: [Things to Note When Learning Lua](https://xxtouch.app/en/docs/handbook/supplement/abc.md)
Path: handbook/supplement/abc.md

# Things to Note When Learning Lua

- Array indices start from 1 (unlike C-like languages that start from 0)
- `string.len` returns the byte count, not the number of characters
- All uninitialized variables are `nil`; assigning `nil` to a table field deletes it
- Only `nil` and `false` are falsy; every other value is truthy, including `0`
- Strings and numbers are automatically converted in arithmetic and comparisons, e.g. `a = '1' + 2`
- Concatenate strings and numbers with `..`, e.g. `a = '1' .. 2`
- Do not compare two floating-point numbers with `==`, e.g. avoid `if 89.7 == (3 * 29.9) then`
- A floating-point number that can be exactly represented as an integer equals that integer (e.g. `1.0 == 1`)

---

Source: [Get Available Memory (sys.available_memory)](https://xxtouch.app/en/docs/handbook/sys/sys.available_memory.md)
Path: handbook/sys/sys.available_memory.md

# Get Available Memory (sys.available_memory)

## Declaration

```lua
mem = sys.available_memory()
```

## Returns

- mem
  Number. Available memory in MB.

## Examples

```lua
sys.alert('Available memory: '..sys.available_memory()..' MB')
```

---

Source: [touch Sample Code](https://xxtouch.app/en/docs/handbook/touch/samples-1.md)
Path: handbook/touch/samples-1.md

# touch Sample Code

## Examples

```lua
-- One-liner style:
touch.on(306, 300):step_len(2):step_delay(0):move(350, 800):msleep(1000):off()
--
-- Expanded style:
touch.on(306, 300)   -- touch at 306,300
    :step_len(2)     -- set step length to 2
    :step_delay(0)   -- set per-step delay to 0
    :move(350, 800)  -- move to 350,800 with the above settings
    :msleep(1000)    -- wait 1000 ms (1 second)
:off()               -- lift finger
--
-- Using a variable:
local te = touch.on(306,300)
te:step_len(2)
te:step_delay(0)
te:move(350, 800)
te:msleep(1000)
te:off()
--
-- Typical slide sequence:
touch.on(306, 300)
    :move(350, 800)
    :msleep(1000)
:off()
--
-- Equivalent one-liner:
touch.on(306, 300):move(350, 800):msleep(1000):off()
--
-- Simulate a tap using on+delay+off:
touch.on(306, 300):msleep(30):off()
--
```

## Tips for fast and precise swipes

```lua
-- A more stable fast-and-precise swipe is usually done like this:
-- quickly go a bit past the target, then move back to the target
touch.on(125, 2000) -- press at start position
    :step_len(10)    -- longer step for a fast swipe
    :step_delay(1)   -- 1ms per step for fast movement
    :move(125, 505 - 20) -- quickly move slightly past the target (upward swipe => smaller y)
    :step_len(1)     -- shorten the step length when moving back to reduce inertia
    :step_delay(20)  -- slow down a bit when moving back for a steadier path
    :move(125, 505)  -- move back to the target position
    :delay(200)      -- wait before lifting
:off()               -- lift finger
```

- The example above is for an upward swipe. For downward, leftward, or rightward swipes, make the “past the target” point slightly beyond the target in that direction.
- If the swipe does not involve a screen edge, usually moving a bit past the target and then moving back to the target is already precise, fast, and free of inertia.
- If that “past the target” point would be outside the screen, that part does not count. In that case, swipe quickly to the screen edge first, then pull back a little, and finally move slowly to the target position.
- Even if the target itself is right on the screen edge, it is still usually more stable to reach the edge first, pull back a little, and then slowly move back to the target.

---

Source: [List Text Elements (ui_element.list_text_elements)](https://xxtouch.app/en/docs/handbook/ui_element/ui_element.list_text_elements.md)
Path: handbook/ui_element/ui_element.list_text_elements.md

# List Text Elements (ui_element.list_text_elements)

> **This function is available in versions after 20260507**

## Declaration

```lua
elements, err = ui_element.list_text_elements([ pid_or_options ])
```

## Parameters

- pid_or_options
  Optional, integer or table. Integer means target app process identifier; table options are described in [Common options](options.md).

[Attribute exclusion options](options.md#attribute-exclusions) are supported **from 20261115**.

## Returns

- elements
  Table. UI element array. `nil` on failure.
- err
  String. Failure reason.

## Description

> Get text elements from the current target app.
> Coordinate fields in returned elements use physical pixels.
> This API is kept for old scripts and uses conservative defaults. For new targeting logic, prefer [`find`](ui_element.find.md) or [`snapshot`](ui_element.snapshot.md).

## Example

```lua
local ui_element = require("ui_element")

local list, err = ui_element.list_text_elements({
    max_level = 1,
    include_hit_state = true,
})

if list then
    for _, item in ipairs(list) do
        if item.text then
            nLog(item.text)
        end
    end
else
    sys.toast(err)
end
```

**Note**: Uses non-chapter APIs [`nLog`](/en/docs/handbook/develop-helper/nLog.md) and [`sys.toast`](/en/docs/handbook/sys/sys.toast.md).

---

Source: [Generate the Next Counter-Based One-Time Password (utils.hotp_next)](https://xxtouch.app/en/docs/handbook/utils/utils.hotp_next.md)
Path: handbook/utils/utils.hotp_next.md

# Generate the Next Counter-Based One-Time Password (utils.hotp_next)

## Declaration

```lua
code, err = utils.hotp_next(url[, secret])
```

## Parameters

- url
  String. HOTP URL in the `otpauth://hotp/...` format.
- secret
  String. Base32 secret. Optional. When provided, this secret is used to generate the code.

## Returns

- code
  String. Generated one-time password.
- err
  String. Error message returned when generation fails.

## Description

> Available after 2026-01-07.
> Generate the next one-time password from an HOTP URL.
> Use [`utils.hotp_counter`](utils.hotp_counter.md) if you need to specify the counter yourself.
> The URL usually contains `secret`, and may also contain `digits` and `algorithm`.
> `algorithm` can be `SHA1`, `SHA256`, or `SHA512`.

## Examples

```lua
local url = "otpauth://hotp/Demo:alice?secret=JBSWY3DPEHPK3PXP&issuer=Demo&digits=6&algorithm=SHA1"

local code, err = utils.hotp_next(url)
if code then
    nLog(code)
else
    nLog(err)
end
```

---

Source: [Overwrite Settings Table to a Domain (xui.write)](https://xxtouch.app/en/docs/handbook/xui/xui.write.md)
Path: handbook/xui/xui.write.md

# Overwrite Settings Table to a Domain (xui.write)

## Declaration

```lua
ok = xui.write(domain, settings)
```

## Parameters

- domain
  String. The defaults domain identifier used by the config UI.
- settings
  Table. Key-value pairs to write.

## Returns

- ok
  Boolean. true on success; false on failure.

## Description

> Use this function to write multiple settings at once; if the config UI is currently displayed, the displayed values are updated immediately.
> This function does not validate value types. If you need to ensure value types are valid, call `xui.setup` after writing to validate/correct.
> See the config UI standard: [XUI](/XUI/README.md)

## Examples

```lua
xui.setup('interface.xui')
local dict = xui.read('com.yourcompany.A-Script-Bundle')
dict['enabled'] = true
xui.write('com.yourcompany.A-Script-Bundle', dict)
xui.setup('interface.xui')
```

---

Source: [Get app icon PNG data by bundle ID (app.png_data_for_bid)](https://xxtouch.app/en/docs/handbook/app/app.png_data_for_bid.md)
Path: handbook/app/app.png_data_for_bid.md

# Get app icon PNG data by bundle ID (app.png_data_for_bid)

## Declaration

```lua
png_data = app.png_data_for_bid(bid)
```

## Parameters

- bid
  String. App bundle identifier. You can find it in `XXT App -> More -> App List`.

## Returns

- png_data
  String | nil. Binary PNG data of the app icon, or nil if the app does not exist.

## Example

```lua
-- Save WeChat icon to photo album
image.load_data(app.png_data_for_bid("com.tencent.xin")):save_to_album()
```
Note: uses non-chapter APIs [`image.load_data`](/en/docs/handbook/image/image.load_data.md) and [`:save_to_album`](/en/docs/handbook/image/imagem_save_to_album.md).

---

Source: [Get device model identifier (device.type)](https://xxtouch.app/en/docs/handbook/device/device.type.md)
Path: handbook/device/device.type.md

# Get device model identifier (device.type)

## Declaration

```lua
type = device.type()
```

## Returns

- type
  String. Device model identifier, e.g. `"iPhone3,1"` or `"iPad13,1"`

## Description

> Get the device type
> This function can be used in XUI

## Example

```lua
if device.type() == "iPhone3,1" then
    -- iPhone 4
end
```

---

Source: [Add a switch (:add_switch)](https://xxtouch.app/en/docs/handbook/dialog/dialogm_add_switch.md)
Path: handbook/dialog/dialogm_add_switch.md

# Add a switch (:add_switch)

## Declaration

```lua
dialog_obj = dialog_obj:add_switch(label [, default_on])
```

## Parameters

- label
  String. The label text shown on the left of the switch
- default_on
  Boolean, optional. Default state, default false (off)

## Returns

- dialog_obj
  Dialog. Returns the dialog itself
- :show() return type
  Boolean. Whether the switch is on

## Description

> Add a switch to the dialog

## Example

```lua
local c, s = dialog():add_switch('A switch', false):show()
sys.alert(s['A switch'])
```
Note: Uses function outside this chapter [`sys.alert`](/en/docs/handbook/sys/sys.alert.md)

## Full example

See [:show()](/en/docs/handbook/dialog/dialogm_show.md)

---

Source: [Remove a specific line (file.remove_line)](https://xxtouch.app/en/docs/handbook/file/file.remove_line.md)
Path: handbook/file/file.remove_line.md

# Remove a specific line (file.remove_line)

## Declaration

```lua
ok, removed = file.remove_line(path, n)
```

## Parameters

- path
  String. Absolute file path.
- n
  Integer. Line number. 0 means last line + 1. Negative means counting from the end.

## Returns

- ok
  Boolean. true if success, false if failure.
- removed
  String. The removed line when success; when failed, returns the error message.

## Description

> Remove the specified line. If the following lines exist, subsequent lines will move forward.
> This function automatically strips UTF-8 BOM at the file head.

## Example

```lua
local success, line = file.remove_line("/var/mobile/1.txt", 3)
if success then
    sys.alert("Success. Removed line: "..line)
else
    sys.alert("Failed: "..line)
end
```
**Note**: Uses [`sys.alert`](/en/docs/handbook/sys/sys.alert.md)

---

Source: [Save image as a JPEG file (:save_to_jpeg_file)](https://xxtouch.app/en/docs/handbook/image/imagem_save_to_jpeg_file.md)
Path: handbook/image/imagem_save_to_jpeg_file.md

# Save image as a JPEG file (:save_to_jpeg_file)

## Declaration

```lua
img:save_to_jpeg_file(path [, quality ])
```

## Parameters

- path
  String. Absolute path to save the JPEG file
- quality
  Number, optional. Image quality, in range 0.0~1.0. Default 1.0

## Description

> Save the image object to a JPEG file. The file extension does not need to be .jpg

## Example

```lua
-- Capture full screen and save to file
screen.image():save_to_jpeg_file("/var/mobile/1.jpg")
```
```lua
-- Save with lower quality (lossy compression)
screen.image():save_to_jpeg_file("/var/mobile/1.jpg", 0.4)
```
Note: This example uses a function outside this chapter [`screen.image`](/en/docs/handbook/screen/screen.image.md)

---

Source: [Release a hardware keyboard key (:up)](https://xxtouch.app/en/docs/handbook/key/hardware_keyboardm_up.md)
Path: handbook/key/hardware_keyboardm_up.md

# Release a hardware keyboard key (:up)

> **This method is available in versions after 20260805**

## Declaration

```lua
success, err = keyboard:up(key)
success, err = keyboard:up(usage_page, usage_id)
```

## Parameters

- key
  String. Uses the same key-name mapping as [`key.press`](/en/docs/handbook/key/key.press.md).
- usage_page
  Integer. Hardware keyboard objects currently accept only Keyboard/Keypad Usage Page `0x07`.
- usage_id
  Integer. Physical key identifier, not a character encoding.

## Returns

- success
  Boolean. Returns `true` when the key is released successfully and `false` on failure.
- err
  String. Error message returned when sending fails.

## Description

> Release a hardware keyboard key previously held by [`:down`](hardware_keyboardm_down.md).

If the same keyboard is running a `:press` or `:send_text` sequence, this method returns `false, "hardware keyboard is busy"`. Failed input is not retried through another input method.

## Example

```lua
local keyboard = assert(key.connect_keyboard())

assert(keyboard:down("LEFTSHIFT"))
assert(keyboard:up("LEFTSHIFT"))

assert(keyboard:disconnect())
```

---

Source: [Pop from back of process queue (proc_queue_pop_back)](https://xxtouch.app/en/docs/handbook/proc/proc_queue_pop_back.md)
Path: handbook/proc/proc_queue_pop_back.md

# Pop from back of process queue (proc_queue_pop_back)

## Declaration

```lua
value = proc_queue_pop_back(key)
```

## Parameters

- key
  String.

## Returns

- value
  String. The popped value. If the queue does not exist or is empty, returns empty string.

## Description

- All process queues whose names start with "xxtouch." or "1ferver." are reserved.
- Pop a value from the back.

## Example

```lua
local billno = proc_queue_pop_back("billnos")
if billno ~= "" then
    print(billno)
else
    print("no bill")
end
```

---

Source: [! OCR Text in Region (screen.ocr_text)](https://xxtouch.app/en/docs/handbook/screen/screen.ocr_text.md)
Path: handbook/screen/screen.ocr_text.md

# ! OCR Text in Region (screen.ocr_text)

## Declaration

```lua
text, details = screen.ocr_text(left, top, right, bottom [, engine_options, binarization_options ])
```

## Parameters

- left, top, right, bottom
  Integer. Region on the screen. `0, 0, 0, 0` means full screen.
- engine_options
  Optional, table. Choose recognition language and engine.
  <details>
  <summary>Structure</summary>

  ```lua
  {
      -- If engine = "apple", iOS 13+ uses Vision.framework
      -- You can use image.vision_supported_recognition_languages() to get available OCR models for Vision.framework
      -- If engine = "paddle", uses Paddle-Lite. You can specify lang, e.g. lang = "ppocr_ch" means model at /var/mobile/Media/1ferver/models/ppocr_ch
      -- Paddle-Lite supports Slim models in *.nb format
      engine = "apple" | "paddle" | "tesseract",
      lang = "zh-Hans",
  }
  ```
  </details>

  <details>
  <summary>Built-in Vision.framework OCR models by iOS version</summary>

  ```lua
  { -- iOS 13
      [1] = "en-US",
  }

  { -- iOS 14~15
      [1] = "en-US",
      [2] = "fr-FR",
      [3] = "it-IT",
      [4] = "de-DE",
      [5] = "es-ES",
      [6] = "pt-BR",
      [7] = "zh-Hans",
      [8] = "zh-Hant",
  }

  { -- iOS 16
      [ 1] = "en-US",
      [ 2] = "fr-FR",
      [ 3] = "it-IT",
      [ 4] = "de-DE",
      [ 5] = "es-ES",
      [ 6] = "pt-BR",
      [ 7] = "zh-Hans",
      [ 8] = "zh-Hant",
      [ 9] = "yue-Hans",
      [10] = "yue-Hant",
      [11] = "ko-KR",
      [12] = "ja-JP",
      [13] = "ru-RU",
      [14] = "uk-UA",
  }
  ```
  </details>
- binarization_options
  Number, threshold. See [Image auto binarization](/en/docs/handbook/image/imagem_cv_binaryzation.md)
  Table, custom color-bias binarization. See [Image manual binarization](/en/docs/handbook/image/imagem_binaryzation.md)
  String, custom color-bias binarization. See [Image manual binarization](/en/docs/handbook/image/imagem_binaryzation.md)

## Returns

- text
  String. Recognized text.
- details
  Table.
  <details>
  <summary>OCR result detail structure</summary>

  ```lua
  {
      {
          ["y"] = number_value,
          ["x"] = number_value,
          ["w"] = number_value,
          ["h"] = number_value,
          ["confidence"] = number_value(0.0000 ~ 1.0000),
          ["text"] = string_value,
      },
      ...
  }
  ```
  </details>

## Description

> Coordinate parameters and return values follow the coordinate system initialized via [`screen.init`](/en/docs/handbook/screen/screen.init.md).
> For backward compatibility, when engine is not specified, the deprecated tesseract engine is used.
> Supported engines Apple and Paddle-Lite require software version 1.3.8 or above.
> [PaddleLite Simplified Chinese standard model (requires extraction)](https://xxtouch.lanzout.com/iL57a38ww71e)
> [PaddleLite Simplified Chinese full model (requires extraction)](https://xxtouch.lanzout.com/iiQYx38ww6fc)
> [PaddleLite Traditional Chinese model (requires extraction)](https://xxtouch.lanzout.com/iNNpU38wyb3c)
> [PaddleLite Japanese model (requires extraction)](https://xxtouch.lanzout.com/iYXfK3boux0h)
> [PaddleLite Korean model (requires extraction)](https://xxtouch.lanzout.com/ieCCH3bouxda)
> [PaddleLite English alphanumeric model (requires extraction)](https://xxtouch.lanzout.com/iiKtE3994q8f)
> You can also download models from the [PaddleOCR model list](https://github.com/PaddlePaddle/PaddleOCR/blob/main/docs/version2.x/ppocr/model_list.md), convert them to `det_opt.nb`, `cls_opt.nb`, and `rec_opt.nb`, and pair them with the appropriate [`dict.txt`](https://github.com/PaddlePaddle/PaddleOCR/tree/main/ppocr/utils/dict)

## Examples

```lua
-- 1.3.8+
text, info = screen.ocr_text(187, 882, 298, 914, "en-US")   -- iOS 13+ recognizes English using built-in en-US model
sys.toast("Result: "..text:atrim())

text, info = screen.ocr_text(187, 882, 298, 914, "zh-Hans") -- iOS 14+ recognizes Simplified Chinese using built-in zh-Hans model
sys.toast("Result: "..text:atrim())

text, info = screen.ocr_text(187, 882, 298, 914, {
    engine = "apple",
    lang = "zh-Hans"
}, "9D5D39-0F1F26,D3D3D2-2C2C2D")
sys.toast("Result: "..text:atrim())

text, info = screen.ocr_text(0, 0, 0, 0, {
    engine = "paddle",
    lang = "ppocr_ch",
})
sys.toast("Result: "..text:atrim())
```
**Note**: Uses [`sys.toast`](/en/docs/handbook/sys/sys.toast.md), [`string.atrim`](/en/docs/handbook/ext-string/string.atrim.md)

## Legacy (Not Recommended)

> The built-in tesseract engine is no longer recommended. It remains the default OCR engine in the current version of XXTouch only to keep old scripts compatible.
> Built-in default OCR engine is tesseract 3.02. Incorrect version or damaged language file may crash XXTouch script service.
> XXTouch bundles `eng` language for [A-Za-z0-9].
> For Simplified Chinese or other languages, copy the language file into `/var/mobile/Media/1ferver/tessdata/`.
> Provided: [Simplified Chinese language file (needs extract)](https://xxtouch.lanzout.com/iAxmN328t23i)

## Legacy Examples (Not Recommended)

```lua
-- Example 1:
local txt = screen.ocr_text(187, 882, 298, 914) -- default is tesseract English digits mode
sys.toast("Result: "..txt:atrim())
--
-- Example 2:
local txt = screen.ocr_text(465, 241, 505, 269, "eng", "9D5D39-0F1F26,D3D3D2-2C2C2D") -- color-bias binarization
sys.toast("Result: "..txt:atrim())
--
-- Example 3:
local txt = screen.ocr_text(465, 241, 505, 269, "eng", { {0x9D5D39, 0x0F1F26}, {0xD3D3D2, 0x2C2C2D} }) -- same as above
sys.toast("Result: "..txt:atrim())
--
-- Example 4:
local txt = screen.ocr_text(187, 882, 298, 914, {
  lang = "chi_sim",         -- tesseract Simplified Chinese (not bundled)
  white_list = "你我他",
})
sys.toast("Result: "..txt:atrim())
--
-- Example 5:
local txt = screen.ocr_text(187, 882, 298, 914, {
  lang = "eng",
  white_list = "1234567890",      -- only digits
}, "9D5D39-0F1F26,D3D3D2-2C2C2D") -- color-bias binarization
sys.toast("Result: "..txt:atrim())
```

---

Source: [Common Runtime Errors Reference](https://xxtouch.app/en/docs/handbook/supplement/runtime-errors.md)
Path: handbook/supplement/runtime-errors.md

# Common Runtime Errors Reference

| Error snippet | Cause | How to fix |
|------|----|----|
|attempt to perform arithmetic on a|Tried arithmetic (`+, -, *, /`) on a non-number|Validate operands are numbers before arithmetic|
|attempt to compare|Tried comparison (`>, <, >=, <=`) on invalid values|Validate both operands are comparable before comparison|
|attempt to concatenate a|Tried concatenating a non-string with `..`|Ensure both sides are strings before concatenation|
|attempt to call a|Tried to call a value that is not a function|Ensure the value is a function before calling|
|attempt to index a|Tried to index (subscript) a non-table value|Ensure the variable is a table before indexing|
|attempt to yield across a C-call boundary|Tried to yield in a context that cannot yield|When using [require](https://www.lua.org/manual/5.3/manual.html#pdf-require), ensure the required module returns without calling yielding functions (marked with exclamation in this handbook). Also avoid using yielding functions in callbacks with C bridges.|
|invalid order function for sorting|Invalid sort comparator; comparison logic is inconsistent|Use a strict order function; it must not be simultaneously a`>`b and a`<`b for any pair|
|bad argument #1 to 'xxx' (number expected, got nil)|Argument #1 to function 'xxx' is invalid; number expected but got nil|Pass a valid argument of the expected type|
|bad argument #2 to 'xxx' (number has no integer representation)|Argument #2 cannot be represented as an integer|Pass a valid argument|
|bad argument #3 to 'xxx'|Argument #3 is invalid|Pass a valid argument|

- Workaround for "attempt to yield across a C-call boundary" when using [require](https://www.lua.org/manual/5.3/manual.html#pdf-require):
  + 1. Add `return function()` to the first line of the required module
  + 2. Add `end` at the last line of the module
  + 3. Add an extra pair of parentheses when requiring: change `require('A')` to `require('A')()`

---

Source: [Get Free Disk Space (sys.free_disk_space)](https://xxtouch.app/en/docs/handbook/sys/sys.free_disk_space.md)
Path: handbook/sys/sys.free_disk_space.md

# Get Free Disk Space (sys.free_disk_space)

## Declaration

```lua
space = sys.free_disk_space([mount_point])
```

## Parameters

- mount_point
  String. Typically `"/var"` for user space or `"/"` for system space. With external storage there may be other values.

## Returns

- space
  Number. Free space in MB.

## Examples

```lua
sys.alert(
    'System space left\n'..sys.free_disk_space('/')..'MB\n\n'..
    'User space left\n'..sys.free_disk_space('/var')..'MB'
)
```

---

Source: [Get UI Element at Position (ui_element.text_element_at_position)](https://xxtouch.app/en/docs/handbook/ui_element/ui_element.text_element_at_position.md)
Path: handbook/ui_element/ui_element.text_element_at_position.md

# Get UI Element at Position (ui_element.text_element_at_position)

> **This function is available in versions after 20260507**

## Declaration

```lua
element, err = ui_element.text_element_at_position(x, y [, pid_or_options ])
```

## Parameters

- x, y
  Integer. Screen coordinate in physical pixels.
- pid_or_options
  Optional, integer or table. Integer means target app process identifier; table options are described in [Common options](options.md).

## Returns

- element
  Table. UI element hit at the coordinate. `nil` on failure.
- err
  String. Failure reason.

## Description

> Use this API when you already know a point and want to read the UI element there, such as after image recognition or OCR.
> This is not a coordinate click API. For fixed-coordinate clicks, use [touch.tap](/en/docs/handbook/touch/touch.tap.md).
> It may fail when the point is blank or the target screen does not expose a readable element there.

## Example

```lua
local ui_element = require("ui_element")

local item, err = ui_element.text_element_at_position(300, 500, {
    include_hit_state = true,
    max_level = 1,
})

if item then
    nLog(item.text or item.value or "")
else
    sys.toast(err)
end
```

**Note**: Uses non-chapter APIs [`nLog`](/en/docs/handbook/develop-helper/nLog.md) and [`sys.toast`](/en/docs/handbook/sys/sys.toast.md).

---

Source: [Timestamp to RFC 1123 String (utils.date_to_rfc1123)](https://xxtouch.app/en/docs/handbook/utils/utils.date_to_rfc1123.md)
Path: handbook/utils/utils.date_to_rfc1123.md

# Timestamp to RFC 1123 String (utils.date_to_rfc1123)

## Declaration

```lua
rfc1123 = utils.date_to_rfc1123(timestamp)
```

## Parameters

- timestamp
  Number. Unix timestamp.

## Returns

- rfc1123
  String. RFC 1123 formatted time string.

## Description

> Available after 2025-02-20.

## Examples

```lua
nLog(utils.date_to_rfc1123(1749490800)) -- Mon, 09 Jun 2025 17:40:00 GMT
nLog(utils.date_to_rfc1123(os.time()))
```

---

Source: [Clear All Settings in a Domain (xui.clear)](https://xxtouch.app/en/docs/handbook/xui/xui.clear.md)
Path: handbook/xui/xui.clear.md

# Clear All Settings in a Domain (xui.clear)

## Declaration

```lua
ok = xui.clear(domain)
```

## Parameters

- domain
  String. The defaults domain identifier used by the config UI.

## Returns

- ok
  Boolean. true on success; false on failure (usually because the specified domain does not exist).

## Description

> This function clears all stored settings under the specified domain at once; if the config UI is currently displayed, the displayed values are updated immediately.
> After clearing, call `xui.setup` to regenerate the default settings for the config UI.
> See the config UI standard: [XUI](/XUI/README.md)

## Examples

```lua
xui.clear('com.yourcompany.A-Script-Bundle')
xui.setup('interface.xui')
```

---

Source: [Get pid by bundle ID (app.pid_for_bid)](https://xxtouch.app/en/docs/handbook/app/app.pid_for_bid.md)
Path: handbook/app/app.pid_for_bid.md

# Get pid by bundle ID (app.pid_for_bid)

## Declaration

```lua
pid = app.pid_for_bid(bid)
```

## Parameters

- bid
  String. App bundle identifier. You can find it in `XXT App -> More -> App List`.

## Returns

- pid
  Integer. The pid if the app is running, otherwise 0.

## Example

```lua
local qqpid = app.pid_for_bid("com.tencent.mqq")
if qqpid ~= 0 then
    sys.alert("QQ is running, pid is: "..qqpid)
else
    sys.alert("QQ is not running")
end
```
Note: uses non-chapter API [`sys.alert`](/en/docs/handbook/sys/sys.alert.md).

---

Source: [Text tokenizer module](https://xxtouch.app/en/docs/handbook/coreml/coreml.tokenizer_module.md)
Path: handbook/coreml/coreml.tokenizer_module.md

# Text tokenizer module

The text tokenizer module turns strings into token ID sequences that can be fed into models.
This layer only handles tokenization, encoding, and reverse decoding. It does not run inference. A common workflow is to encode text into `MLMultiArray` or `onnxruntime.tensor`, then pass the result into the matching CoreML or ONNX Runtime request.

The current goal of this module is “good enough for on-device inference”:

- `WordPiece` has the highest compatibility and works well for models such as `BERT` and `CN-CLIP`
- `BPE` and `SentencePiece` use lightweight compatibility-oriented implementations suitable for most on-device encoding cases
- It does not try to bring tokenizer training, sampling, or the entire upstream ecosystem into runtime

> **This module is available in versions released after 20260319**

## Create a tokenizer

### `coreml.new_text_tokenizer(opts)`

```lua
tokenizer, err = coreml.new_text_tokenizer({
    type = tokenizer_type,
    vocab_path = vocab_path,
    merges_path = merges_path,
    model_path = sentencepiece_model_path,
    pattern = regex_pattern,
    context_length = context_length,
    do_lower_case = do_lower_case,
    vocab_limit = vocab_limit,
    clean_text = clean_text,
    add_bos = add_bos,
    add_eos = add_eos,
    bos_token = bos_token,
    eos_token = eos_token,
    pad_token = pad_token,
    unk_token = unk_token,
})
```

### `type` values

- `wordpiece` / `bert` / `cn_clip`
- `bpe` / `gpt2_bpe` / `clip_bpe`
- `sentencepiece` / `spm`
- `regex` / `pattern`
- `byte` / `bytes`
- `whitespace` / `space`
- `character` / `char`

The default is `wordpiece`.

If the first argument to `coreml.new_text_tokenizer(...)` is not a table, the call falls back to the WordPiece shortcut path, which is equivalent to usages such as `coreml.new_wordpiece_tokenizer(vocab_path)`.

### Common parameters

- `vocab_path`
  String. Path to the vocabulary file.

- `merges_path`
  String. Path to the merges file used by BPE tokenizers.

- `model_path`
  String. Path to a `.model` file used by the lightweight SentencePiece-compatible mode.

- `pattern`
  String. Regular expression used by the regex tokenizer.

- `context_length`
  Integer, optional. Output token sequence length.

- `do_lower_case`
  Boolean, optional. Whether to lowercase the input first.

- `vocab_limit`
  Integer, optional. Mostly useful for WordPiece, to cap the effective vocabulary size.

- `clean_text`
  Boolean, optional. Whether to run basic text cleanup before tokenization.

- `add_bos / add_eos`
  Boolean, optional. Whether to prepend / append begin-of-sequence and end-of-sequence tokens.

- `bos_token / eos_token / pad_token / unk_token`
  String, optional. Token text used for the corresponding special token.

Not every tokenizer type supports every field above. The current implementation behaves as follows:

- `wordpiece`
  Accepts either a `vocab_path` string or an options table; requires `vocab_path`; defaults to `context_length = 52`, `do_lower_case = true`, and `vocab_limit = 21128`; the vocab must contain `[PAD]`, `[UNK]`, `[CLS]`, and `[SEP]`
- `bpe`
  Table only; requires `vocab_path` and `merges_path`; defaults to `context_length = 77`, `do_lower_case = false`, `clean_text = false`, `add_bos = false`, and `add_eos = false`
- `sentencepiece`
  Table only; requires at least one of `vocab_path` or `model_path`; defaults to `context_length = 77`, `do_lower_case = false`, `clean_text = true`, `bos_token = "<s>"`, `eos_token = "</s>"`, `pad_token = "<pad>"`, and `unk_token = "<unk>"`
- `regex`
  Table only; requires `vocab_path` and `pattern`; defaults to `context_length = 77`, `do_lower_case = false`, and `clean_text = true`
- `whitespace` / `character` / `byte`
  Table only; require `vocab_path`; default to `context_length = 77`, `do_lower_case = false`, and `clean_text = true`

Selection guide:

- If the model uses `vocab.txt + WordPiece`, choose `wordpiece`
- If the model uses `vocab.json + merges.txt`, choose `bpe`
- If the model uses `.vocab` or `.model`, choose `sentencepiece`
- Use `regex`, `whitespace`, `character`, or `byte` only for simple rule-based cases

### Returns

- tokenizer
  Text tokenizer object, or `nil` on failure.

- err
  String. `nil` on success; error message on failure.

### Notes

- Tokenizer objects are intended to be created once and reused
- Creation mainly decides three things: tokenization algorithm, vocabulary source, and fixed output length
- If model behavior looks wrong, first verify the tokenizer type, vocabulary file, special-token configuration, and `context_length`
- `WordPiece` is currently the most complete and reliable option
- `BPE` and `SentencePiece` aim for practical on-device compatibility rather than reproducing every upstream implementation detail bit-for-bit

## Shortcut constructors

The following helpers are thin wrappers around `coreml.new_text_tokenizer(...)`. Use them when the tokenizer type is already known.

### `coreml.new_wordpiece_tokenizer(opts)`

- Equivalent to `coreml.new_text_tokenizer({ type = "wordpiece", ... })`
- Suitable for `BERT`, `CN-CLIP`, and other WordPiece-style text models
- Also supports passing the vocab path string directly: `coreml.new_wordpiece_tokenizer(vocab_path)`

### `coreml.new_bpe_tokenizer(opts)`

- Equivalent to `coreml.new_text_tokenizer({ type = "bpe", ... })`
- Also covers GPT-2- and CLIP-style `vocab.json + merges.txt` models

### `coreml.new_sentencepiece_tokenizer(opts)`

- Equivalent to `coreml.new_text_tokenizer({ type = "sentencepiece", ... })`
- Uses the lightweight compatibility-oriented implementation
- Supports both `.vocab` and `.model`

### `coreml.new_regex_tokenizer(opts)`

- Equivalent to `coreml.new_text_tokenizer({ type = "regex", ... })`
- Suitable for rule-based tokenization and simple vocabulary lookup

### `coreml.new_byte_tokenizer(opts)`

- Equivalent to `coreml.new_text_tokenizer({ type = "byte", ... })`
- Converts text into UTF-8 bytes first, then looks up tokens by byte value

### `coreml.new_whitespace_tokenizer(opts)`

- Equivalent to `coreml.new_text_tokenizer({ type = "whitespace", ... })`
- Suitable for whitespace tokenization with direct vocabulary lookup

### `coreml.new_character_tokenizer(opts)`

- Equivalent to `coreml.new_text_tokenizer({ type = "character", ... })`
- Suitable for character-level models

## Type check

### `coreml.is_text_tokenizer(value)`

```lua
is_tokenizer = coreml.is_text_tokenizer(value)
```

Checks whether a value is a `coreml_text_tokenizer_object`.

## Object methods

### `:encode(text[, opts])`

```lua
result, err = tokenizer:encode(text)
```

or

```lua
result, err = tokenizer:encode(text, {
    output = "table" or "MLMultiArray" or "ort_tensor",
    data_type = data_type,
    pair_text = paired_text,
    max_length = max_length,
    padding = padding_strategy,
    truncation = truncation_strategy,
    return_attention_mask = return_attention_mask,
    return_token_type_ids = return_token_type_ids,
    return_special_tokens_mask = return_special_tokens_mask,
})
```

Encodes a single text string into a token sequence.

### `:encode_batch(texts[, opts])`

```lua
result, err = tokenizer:encode_batch(texts)
```

or

```lua
result, err = tokenizer:encode_batch(texts, {
    output = "table" or "MLMultiArray" or "ort_tensor",
    data_type = data_type,
    pair_text = paired_text_or_array,
    max_length = max_length,
    padding = padding_strategy,
    truncation = truncation_strategy,
    return_attention_mask = return_attention_mask,
    return_token_type_ids = return_token_type_ids,
    return_special_tokens_mask = return_special_tokens_mask,
})
```

Encodes multiple texts at once and returns token sequences in batch form.

### `:decode(ids)`

```lua
text, err = tokenizer:decode(ids)
```

Reverse-decodes a **single** token ID sequence back into text.

- `ids` may be a Lua array, an `MLMultiArray`, or tensor-like userdata such as an ORT tensor
- `ids` may also be any tensor-like userdata that implements both `shape()` and `to_table()`
- Passing batch data is an error; use `decode_batch()` for that case

### `:decode_batch(batch_ids)`

```lua
texts, err = tokenizer:decode_batch(batch_ids)
```

Reverse-decodes a batch of token ID sequences into a Lua string array.

- `batch_ids` may be a nested Lua array, an `MLMultiArray`, or tensor-like userdata such as an ORT tensor
- `batch_ids` may also be any tensor-like userdata that implements both `shape()` and `to_table()`

### `:vocab_size()`

```lua
size = tokenizer:vocab_size()
```

Returns the available vocabulary size.

### `:context_length()`

```lua
length = tokenizer:context_length()
```

Returns the tokenizer's fixed output length.

## Encoding and return-value notes

- `output` defaults to `"MLMultiArray"`, which is convenient when the result goes straight into a CoreML model
- `output = "table"` is useful for debugging, inspecting token IDs, or supporting older scripts
- `output = "ort_tensor"` is useful when the result should go directly into an ONNX Runtime text model
- `output = "ort_tensor"` requires `require("onnxruntime")` first, because the ORT bridge is injected at that time
- `output = "ort_tensor"` depends on ONNX Runtime and therefore requires **iOS 13+**
- For compatibility with older scripts, the legacy field `multi_array_output` is still read; new code should prefer `output`

### `data_type` rules

- With `output = "MLMultiArray"`, `data_type` can be `"int32"`, `"float32"`, `"float16"`, or `"double"`; `"float64"` is accepted as an alias for `"double"`
- With `output = "MLMultiArray"`, the default `data_type` is `"int32"`
- With `output = "ort_tensor"`, `data_type` can be `"float16"`, `"float32"`, `"uint8"`, `"int8"`, `"int32"`, `"int64"`, `"double"`, or `"bool"`
- With `output = "ort_tensor"`, the default `data_type` is `"int64"`

### `padding` / `truncation`

- `padding` can be a boolean or a string
  - `true` maps to `"max_length"`
  - `false` maps to `"do_not_pad"`
- `truncation` can be a boolean or a string
  - `true` maps to `"longest_first"`
  - `false` maps to `"do_not_truncate"`

### `pair_text`

- `encode()` accepts a single `pair_text`
- `encode_batch()` accepts either one shared `pair_text` or an array of pair texts matching the batch size

### Structured returns

When any of the following options is `true`, `encode()` / `encode_batch()` return a structured result table instead of a bare token sequence:

- `return_attention_mask`
- `return_token_type_ids`
- `return_special_tokens_mask`

Common fields in the structured result:

- `input_ids`
- `length`
- `attention_mask`
- `token_type_ids`
- `special_tokens_mask`

For batch encoding:

- With `output = "table"`, each sample keeps its own natural length
- With `output = "MLMultiArray"` or `"ort_tensor"`, the batch is padded into a rectangular form before returning

## Example

```lua
local tokenizer = assert(coreml.new_text_tokenizer({
    type = "wordpiece",
    vocab_path = XXT_HOME_PATH.."/models/demo/vocab.txt",
    context_length = 52,
}))

local ids = assert(tokenizer:encode("stars", {
    output = "MLMultiArray",
    data_type = "int32",
}))

local structured = assert(tokenizer:encode("stars", {
    output = "table",
    return_attention_mask = true,
    return_token_type_ids = true,
}))

local ort = require("onnxruntime")

local input_ids = assert(tokenizer:encode("stars", {
    output = "ort_tensor",
    data_type = "int64",
}))

local batch = assert(tokenizer:encode_batch({
    "stars",
    "moon",
}, {
    output = "ort_tensor",
}))

print(tokenizer:decode(structured.input_ids))
print(tokenizer:vocab_size())
print(tokenizer:context_length())
```

---

Source: [Get device name (device.name)](https://xxtouch.app/en/docs/handbook/device/device.name.md)
Path: handbook/device/device.name.md

# Get device name (device.name)

## Declaration

```lua
name = device.name()
```

## Returns

- name
  String. The user-assigned device name

## Description

> This function can be used in XUI

## Example

```lua
sys.alert("Device name: " .. device.name())
```
Note: Uses function outside this chapter [`sys.alert`](/en/docs/handbook/sys/sys.alert.md)

---

Source: [Add a picker (:add_picker)](https://xxtouch.app/en/docs/handbook/dialog/dialogm_add_picker.md)
Path: handbook/dialog/dialogm_add_picker.md

# Add a picker (:add_picker)

## Declaration

```lua
dialog_obj = dialog_obj:add_picker(label, options [, default_option])
```

## Parameters

- label
  String. The label text shown on the left of the picker
- options
  Table. Ordered list of option names; names must be unique
- default_option
  String, optional. Default selected option name. Default: first option

## Returns

- dialog_obj
  Dialog. Returns the dialog itself
- :show() return type
  String. The selected option name

## Description

> Add a picker to the dialog

## Example

```lua
local c, s = dialog():add_picker('A picker', {'Choice1', 'Choice2', 'Choice3'}):show()
sys.alert('Your choice: ' .. s['A picker'])
```
Note: Uses function outside this chapter [`sys.alert`](/en/docs/handbook/sys/sys.alert.md)

## Full example

See [:show()](/en/docs/handbook/dialog/dialogm_show.md)

---

Source: [Get all lines from a text file (file.get_lines)](https://xxtouch.app/en/docs/handbook/file/file.get_lines.md)
Path: handbook/file/file.get_lines.md

# Get all lines from a text file (file.get_lines)

## Declaration

```lua
lines, err = file.get_lines(path)
```

## Parameters

- path
  String. Absolute file path.

## Returns

- lines
  Array or nil. Returns an array. nil if file does not exist.
- err
  String. Error message when operation fails.

## Description

> Get all lines from a text file. Empty file returns 0 lines.
> This function automatically strips UTF-8 BOM at the file head.

## Example

```lua
local lines = file.get_lines("/var/mobile/1.txt")
if lines then
    if #lines > 0 then
        sys.alert("First line is "..lines[1])
    else
        sys.alert("File is empty")
    end
else
    sys.alert("Operation failed")
end
```
**Note**: Uses [`sys.alert`](/en/docs/handbook/sys/sys.alert.md), [`string.strip_utf8_bom`](/en/docs/handbook/ext-string/string.strip_utf8_bom.md)

---

Source: [Get PNG data of an image (:png_data)](https://xxtouch.app/en/docs/handbook/image/imagem_png_data.md)
Path: handbook/image/imagem_png_data.md

# Get PNG data of an image (:png_data)

## Declaration

```lua
png_data = img:png_data()
```

## Returns

- png_data
  String. PNG data. Modifying this data will not affect the image object

## Description

> Obtain the PNG data of the image object
> Performance: this function copies data twice

## Example

```lua
file.writes('/var/mobile/1.png', screen.image():png_data())
```
Note: This example uses functions outside this chapter [`screen.image`](/en/docs/handbook/screen/screen.image.md), [`file.writes`](/en/docs/handbook/file/file.writes.md)

---

Source: [! Press a hardware keyboard key (:press)](https://xxtouch.app/en/docs/handbook/key/hardware_keyboardm_press.md)
Path: handbook/key/hardware_keyboardm_press.md

# ! Press a hardware keyboard key (:press)

> **This method is available in versions after 20260805**

## Declaration

```lua
success, err = keyboard:press(key[, press_delay_ms])
success, err = keyboard:press(usage_page, usage_id[, press_delay_ms])
```

## Parameters

- key
  String. Uses the same key-name mapping as [`key.press`](/en/docs/handbook/key/key.press.md).
- usage_page
  Integer. Hardware keyboard objects currently accept only Keyboard/Keypad Usage Page `0x07`.
- usage_id
  Integer. Physical key identifier, not a character encoding.
- press_delay_ms
  Number. Optional. How long to hold the key, in milliseconds. Default: 10 milliseconds.

## Returns

- success
  Boolean. Returns `true` when the key is pressed and released successfully and `false` on failure.
- err
  String. Error message returned when the operation fails.

## Description

> Press the target key, wait for the specified duration, and then release it. Waiting may yield; other [threads](/en/docs/handbook/thread/index.md) may run before the method returns.

- This method preserves ordinary keys and modifier keys that were already held before the call.
- If the same hardware keyboard is already running a `:press` or `:send_text` sequence, the new operation returns `false, "hardware keyboard is busy"`.
- Failed input is not retried through another input method.

## Example

```lua
local keyboard = assert(key.connect_keyboard())

assert(keyboard:press("a"))
assert(keyboard:press(0x07, 4, 30)) -- Keyboard A, held for 30 ms

assert(keyboard:disconnect())
```

---

Source: [Pop all specified values from process queue (proc_queue_pop_value)](https://xxtouch.app/en/docs/handbook/proc/proc_queue_pop_value.md)
Path: handbook/proc/proc_queue_pop_value.md

# Pop all specified values from process queue (proc_queue_pop_value)

## Declaration

```lua
count = proc_queue_pop_value(key, target_value)
```

## Parameters

- key
  String.
- target_value
  String. The value to remove.

## Returns

- count
  Integer. Number of removed values.

## Description

- Available for versions after 20250106.
- All process queues whose names start with "xxtouch." or "1ferver." are reserved.
- Pop all specified values and return the count.

## Example

```lua
local count = proc_queue_pop_value("billnos", "name")
if count ~= 0 then
    print(count)
else
    print("no bill")
end
```

---

Source: [Find image on screen (screen.find_image)](https://xxtouch.app/en/docs/handbook/screen/screen.find_image.md)
Path: handbook/screen/screen.find_image.md

# Find image on screen (screen.find_image)

## Declarations

```lua
x, y = screen.find_image(image [, confidence, left, top, right, bottom ])
results = screen.find_image(image [, options, left, top, right, bottom ])
```

## Parameters

- image
  String: the image data to search for, in PNG or JPEG format.
  Image object: an image object (see [Image module (image)](/en/docs/handbook/image/index.md)).
  Text: path to the image file to search for. If the path is not valid, it will be parsed as raw image data.
- confidence
  Integer, optional. Default 95. Only positions whose confidence is not less than this value will be returned. Range: 0 ~ 100.
- options
  Table, optional.
  <details>
  <summary>Structure</summary>

  ```lua
  {
      find_all = false | true, -- Optional. When true, find all matches; return value is a table. Default false
      confidence_threshold = number_value(0.0 ~ 100.0), -- Optional. Results with confidence >= this are valid. Default 95
      downscale = number_value(0.1 ~ 1.0), -- Optional. Smaller = faster but less precise. Default 1.0 (accuracy first)
      mask = image_object, -- Optional. Marks valid areas of the template image. A binary image of the same size as img; white = valid, black = invalid. Default: all areas valid
  }
  ```
  </details>
- left, top, right, bottom
  Integers, optional. Search region. Default: full screen.

## Returns

- x, y
  Integers. When `options.find_all` is not true, return only the coordinates of the most confident valid match. If none meets the threshold, returns -1, -1.
- results
  Table.
  <details>
  <summary>When options.find_all is true, returns multiple results with confidence >= options.confidence_threshold</summary>

  ```lua
  {
      {
          x = integer_value,
          y = integer_value,
          confidence = number_value(0.0 ~ 100.0),
      },
      ...
  }
  ```
  </details>

## Description

> Find the position of a small image on the screen. This function relies on the image.cv module.
> Coordinate parameters and return values follow the coordinate system initialized via [`screen.init`](/en/docs/handbook/screen/screen.init.md).
> Note: For multi‑resolution compatibility, it is recommended to capture the template on the smallest‑resolution device; screenshots from higher‑resolution devices may not be found on lower‑resolution ones.

### Enhancements in version 1.3.8 and later

- Support finding all matches above the confidence threshold via find_all mode.
- Support downscale to speed up by lowering precision.
- Support mask to mark valid areas in the template for irregular‑shape matching.

## Examples

[XXT Picker for Windows.7z](https://github.com/havonz/XXTouchDebs/raw/refs/heads/master/%E7%9B%B8%E5%85%B3%E8%B5%84%E6%BA%90/XXT%20%E5%8F%96%E8%89%B2%E5%99%A8%201.0.36%20For%20Windows.7z)
```lua
-- Example 1 (Use XXT Picker: Shift + Left Click to box the region; code like this is generated):
x, y = screen.find_image( -- Original position TL: 354,274 | BR: 358,284
"\x89\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\x00\x00\x04\x00\x00\x00\x0a\x08\x02\x00\x00\x00\x1c\x99\x68\x59\x00\x00\x00\x61\x49\x44\x41\x54\x78\xda\x63\x78\xfd\xf4\xda\xff\xff\xff\xff\xfd\xfb\xf7\xed\xcb\x5b\x86\xf7\xaf\x1f\xfc\x87\x01\x86\x2f\x1f\x5f\x02\xa9\xef\xa7\xce\x7c\xdd\xb1\x9b\xe1\xe7\xf7\xcf\x40\xce\xeb\xb2\xea\x7b\xb2\x6a\x0c\x7f\xff\xfe\x01\x72\x9e\x78\x06\x82\x38\x20\xdd\xbf\x7e\xdd\x57\xd4\x82\x72\x7e\xdd\xba\x0d\x64\x41\x39\x08\xd3\x80\x38\x6b\xe3\x7f\x86\x2a\x30\x02\x72\x8c\xa6\x40\x39\x00\xd5\x7b\x5f\x2e\xfd\xba\xd5\x32\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82"
, 95, 0, 0, 639, 1135)
--
-- Example 2:
img = image.load_file("/var/mobile/1.png")
x, y = screen.find_image(img)
x, y = screen.find_image(img, 95)
--
-- Example 4:
x, y = screen.find_image("/var/mobile/1.png", 95, 0, 0, 639, 1135)

-- Example 5 (added in 1.3.8): find multiple targets on full screen
img = image.load_file(XXT_SCRIPTS_PATH..'/1.png')
rets = screen.find_image(img, {
    confidence_threshold = 90, -- valid if confidence >= this value
    downscale = 0.5, -- speed up by lowering precision
    find_all = true, -- find all matches; returns an array of match entries
}, 0, 0, 0, 0) -- region 0,0,0,0 means full screen
```

Note: In Lua string literals, a sequence starting with `\x` followed by two hex digits denotes a single byte with that value. For printable characters, see the ASCII reference.

## Complex example

```lua
-- Download a small image (part of XXTouch icon) and then find it on screen and tap it
local c, h, r = http.get("https://www.xxtouch.app/img/find_image_test.png", 10)
if (c == 200) then
    local img = image.load_data(r)
    if img then
        x, y = screen.find_image(img, 95)
        if x~=-1 then
            touch.tap(x, y)
        else
            sys.alert("XXTouch icon not found on screen")
        end
    else
        sys.alert("Downloaded data is not a valid image")
    end
else
    sys.alert("Download failed")
end
```
**Note**: Uses functions outside this chapter: [`sys.alert`](/en/docs/handbook/sys/sys.alert.md), [`image.load_data`](/en/docs/handbook/image/image.load_data.md), [`touch.tap`](/en/docs/handbook/touch/touch.tap.md), [`http.get`](/en/docs/handbook/http/http.get.md)

---

Source: [Print System Log (sys.log)](https://xxtouch.app/en/docs/handbook/sys/sys.log.md)
Path: handbook/sys/sys.log.md

# Print System Log (sys.log)

## Declaration

```lua
sys.log(...)
```

## Parameters

- ...
  Any number of arguments of any type. Items are separated by tabs in the output.

## Description

> Prints a standard system log.
> You can view logs live via your desktop browser at https://`<device-ip>`:46952/log.html
> Logs are also stored at /var/mobile/Media/1ferver/log/sys.log
> The sys.log file is capped at about 4000 lines; older lines are removed.

## Examples

```lua
sys.log("Hello World, of course")
```

---

Source: [Find One UI Element (ui_element.find)](https://xxtouch.app/en/docs/handbook/ui_element/ui_element.find.md)
Path: handbook/ui_element/ui_element.find.md

# Find One UI Element (ui_element.find)

> **This function is available in versions after 20260507**

## Declaration

```lua
element, err = ui_element.find(selector [, options ])
```

## Parameters

- selector
  Table. Describes the target UI element. See [Selector fields](selector.md).
- options
  Optional, table. See [Common options](options.md).

## Returns

- element
  Table. First matched UI element. `nil` on failure.
- err
  String. Failure reason. When no element matches, it is usually `"target not found"`.

## Description

> If `selector.index` exists, the Nth matched element is returned.
> Prefer `title` or `text_contains` with `role` to reduce ambiguity.

## Example

```lua
local ui_element = require("ui_element")

local item, err = ui_element.find({
    title = "Search",
    role = "text_field",
})

if item then
    ui_element.click(item)
else
    sys.toast(err)
end
```

**Note**: Uses non-chapter API [`sys.toast`](/en/docs/handbook/sys/sys.toast.md).

---

Source: [RFC 1123 String to Timestamp (utils.date_from_rfc1123)](https://xxtouch.app/en/docs/handbook/utils/utils.date_from_rfc1123.md)
Path: handbook/utils/utils.date_from_rfc1123.md

# RFC 1123 String to Timestamp (utils.date_from_rfc1123)

## Declaration

```lua
ts = utils.date_from_rfc1123(rfc1123)
```

## Parameters

- rfc1123
  String. RFC 1123 formatted time string.

## Returns

- ts
  Number. Unix timestamp.

## Description

> Available after 2025-02-20.

## Examples

```lua
nLog(utils.date_from_rfc1123("Mon, 09 Jun 2025 17:40:00 GMT")) -- 1749490800.0
```

---

Source: [Get current memory usage (app.used_memory)](https://xxtouch.app/en/docs/handbook/app/app.used_memory.md)
Path: handbook/app/app.used_memory.md

# Get current memory usage (app.used_memory)

## Declaration

```lua
mem = app.used_memory(bid_or_pid)
```

## Parameters

- bid_or_pid
  String (bundle id) or Integer (pid).

## Returns

- mem
  Number | nil. Memory usage in MB if the app is running, otherwise nil.

## Example

```lua
local qqmem = app.used_memory("com.tencent.mqq")
sys.alert("QQ memory usage: "..qqmem.." MB")
```
Note: uses non-chapter API [`sys.alert`](/en/docs/handbook/sys/sys.alert.md).

---

Source: [Set device name (device.set_name)](https://xxtouch.app/en/docs/handbook/device/device.set_name.md)
Path: handbook/device/device.set_name.md

# Set device name (device.set_name)

## Declaration

```lua
device.set_name(name)
```

## Parameters

- name
  String. The device name to set

## Description

> Note: Setting device name may take effect with a delay on different iOS versions
> That is, calling device.set_name and then immediately calling device.name may not return the new name
> In such cases, add an appropriate delay depending on OS version

## Example

```lua
device.set_name("iPhavonz")
```

---

Source: [Add a radio group (:add_radio)](https://xxtouch.app/en/docs/handbook/dialog/dialogm_add_radio.md)
Path: handbook/dialog/dialogm_add_radio.md

# Add a radio group (:add_radio)

## Declaration

```lua
dialog_obj = dialog_obj:add_radio(label, options [, default_option])
```

## Parameters

- label
  String. Title text for the radio group
- options
  Table. Ordered list of option names; names must be unique
- default_option
  String, optional. Selected option name. Default: first option

## Returns

- dialog_obj
  Dialog. Returns the dialog itself
- :show() return type
  String. The selected option name

## Description

> Add a radio group to the dialog

## Example

```lua
local c, s = dialog():add_radio('A radio group', {'R1', 'R2', 'R3'}):show()
sys.alert('Your choice: ' .. s['A radio group'])
```
Note: Uses function outside this chapter [`sys.alert`](/en/docs/handbook/sys/sys.alert.md)

## Full example

See [:show()](/en/docs/handbook/dialog/dialogm_show.md)

---

Source: [Write a sequence (array) to file line by line (file.set_lines)](https://xxtouch.app/en/docs/handbook/file/file.set_lines.md)
Path: handbook/file/file.set_lines.md

# Write a sequence (array) to file line by line (file.set_lines)

## Declaration

```lua
ok, err = file.set_lines(path, lines)
```

## Parameters

- path
  String. Absolute file path.
- lines
  Array. Lines to write.

## Returns

- ok
  Boolean. true if success, false if failure.
- err
  String. Error message when operation fails.

## Description

> Convert an array to lines and overwrite the file. Creates file if it does not exist. Returns false if directory does not exist.
> This function automatically strips UTF-8 BOM at the file head.

## Example

```lua
local success, err = file.set_lines("/var/mobile/1.txt", {
    "The quick brown fox",
    "jumps over the lazy dog",
})
if success then
    sys.alert("Lines written successfully")
else
    sys.alert("Failed: "..err)
end
```
**Note**: Uses [`sys.alert`](/en/docs/handbook/sys/sys.alert.md)

---

Source: [Get JPEG data of an image (:jpeg_data)](https://xxtouch.app/en/docs/handbook/image/imagem_jpeg_data.md)
Path: handbook/image/imagem_jpeg_data.md

# Get JPEG data of an image (:jpeg_data)

## Declaration

```lua
jpeg_data = img:jpeg_data([ quality ])
```

## Parameters

- quality
  Number, optional. Image quality, 0.0~1.0. Default 1.0

## Returns

- jpeg_data
  String. JPEG data. Modifying this data will not affect the image object

## Description

> Obtain the JPEG data of the image object
> Performance: this function copies data twice

## Example

```lua
-- Save full-screen image with 80% quality (lossy compression)
file.writes('/var/mobile/1.jpg', screen.image():jpeg_data(0.8))
```
Note: This example uses functions outside this chapter [`screen.image`](/en/docs/handbook/screen/screen.image.md), [`file.writes`](/en/docs/handbook/file/file.writes.md)

---

Source: [! Type text with a hardware keyboard (:send_text)](https://xxtouch.app/en/docs/handbook/key/hardware_keyboardm_send_text.md)
Path: handbook/key/hardware_keyboardm_send_text.md

# ! Type text with a hardware keyboard (:send_text)

> **This method is available in versions after 20260805**

## Declaration

```lua
success, err = keyboard:send_text(text[, type_delay_ms, shift_delay_ms])
```

## Parameters

- text
  String. Text to type. Only English letters, digits, spaces, half-width symbols, and escape sequences `"\b"`, `"\r"`, and `"\t"` are supported.
- type_delay_ms
  Number. Optional. Delay between key operations in milliseconds. Default: 0.
- shift_delay_ms
  Number. Optional. Delay around pressing or releasing Shift in milliseconds. Default: 0.

## Returns

- success
  Boolean. Returns `true` after all text is sent successfully and `false` on failure.
- err
  String. Error message returned when sending fails.

## Description

> Generate key and Shift combinations using the current Lua US keyboard mapping. Waiting during input may yield; other [threads](/en/docs/handbook/thread/index.md) may run before the method returns.

- The resulting characters are still affected by the target system's keyboard layout.
- This method preserves ordinary keys and modifier keys that were already held before the call.
- If the same hardware keyboard is already running a `:press` or `:send_text` sequence, the new operation returns `false, "hardware keyboard is busy"`.
- Failed input is not retried through another input method.

## Example

```lua
local keyboard = assert(key.connect_keyboard())

assert(keyboard:send_text("Hello"))
assert(keyboard:send_text("Hello", 30, 10))

assert(keyboard:disconnect())
```

---

Source: [Count occurrences of a value in process queue (proc_queue_count_value)](https://xxtouch.app/en/docs/handbook/proc/proc_queue_count_value.md)
Path: handbook/proc/proc_queue_count_value.md

# Count occurrences of a value in process queue (proc_queue_count_value)

## Declaration

```lua
count = proc_queue_count_value(key, target_value)
```

## Parameters

- key
  String.
- target_value
  String. The value to count.

## Returns

- count
  Integer. Number of occurrences of the value in the queue.

## Description

- Available for versions after 20250106.
- All process queues whose names start with "xxtouch." or "1ferver." are reserved.
- Count occurrences of a specific value in a queue.

## Example

```lua
local count = proc_queue_count_value("billnos", "name")
if count ~= 0 then
    print(count)
else
    print("no bill")
end
```

---

Source: [Rotate Coordinates (screen.rotate_xy)](https://xxtouch.app/en/docs/handbook/screen/screen.rotate_xy.md)
Path: handbook/screen/screen.rotate_xy.md

# Rotate Coordinates (screen.rotate_xy)

## Declaration

```lua
rx, ry = screen.rotate_xy(x, y, rotation)
```

## Parameters

- x, y
  Integer. Coordinates to rotate.
- **rotation**
  0 = no rotation
  1 = rotate left 90°
  2 = rotate right 90°
  3 = rotate 180°

## Returns

- rx, ry
  Integer. Coordinates after applying the specified **rotation**.

## Description

> Rotate coordinates, typically used to convert portrait coordinates to landscape: `init(0) -> init(rotation)`.

## Example

```lua
rx, ry = screen.rotate_xy(100, 200, 1)
```

---

Source: [Send Signal to PID (sys.kill)](https://xxtouch.app/en/docs/handbook/sys/sys.kill.md)
Path: handbook/sys/sys.kill.md

# Send Signal to PID (sys.kill)

## Declaration

```lua
sys.kill(pid, signal)
```

## Parameters

- pid
  Integer. Process ID.
- signal
  Integer. Signal number.

## Description

> Sends a signal to the specified PID.

## Examples

```lua
-- Force quit the foreground app
sys.kill(app.front_pid(), 9)
```
Note: uses [`app.front_pid`](/en/docs/handbook/app/app.front_pid.md).

---

Source: [Find Multiple UI Elements (ui_element.find_all)](https://xxtouch.app/en/docs/handbook/ui_element/ui_element.find_all.md)
Path: handbook/ui_element/ui_element.find_all.md

# Find Multiple UI Elements (ui_element.find_all)

> **This function is available in versions after 20260507**

## Declaration

```lua
elements = ui_element.find_all(selector [, options ])
```

## Parameters

- selector
  Table. Describes the target UI elements. See [Selector fields](selector.md).
- options
  Optional, table. See [Common options](options.md).

## Returns

- elements
  Table. Array of all matched elements. Returns an empty array when no element matches.

## Description

> `find_all` is useful for enumerating controls of the same type or checking match count first.
> If you only need the first match, use [`find`](ui_element.find.md).

## Example

```lua
local ui_element = require("ui_element")

local items = ui_element.find_all({
    role = "button",
})

for i, item in ipairs(items) do
    nLog(i, item.text or "")
end
```

**Note**: Uses non-chapter API [`nLog`](/en/docs/handbook/develop-helper/nLog.md).

---

Source: [Timestamp to RFC 3339 String (utils.date_to_rfc3339)](https://xxtouch.app/en/docs/handbook/utils/utils.date_to_rfc3339.md)
Path: handbook/utils/utils.date_to_rfc3339.md

# Timestamp to RFC 3339 String (utils.date_to_rfc3339)

## Declaration

```lua
rfc3339 = utils.date_to_rfc3339(timestamp)
```

## Parameters

- timestamp
  Number. Unix timestamp.

## Returns

- rfc3339
  String. RFC 3339 formatted time string.

## Description

> Available after 2025-02-20.

## Examples

```lua
nLog(utils.date_to_rfc3339(1749490800)) -- 2025-06-09T17:40:00.000Z
nLog(utils.date_to_rfc3339(os.time()))
```

---

Source: [Get foreground app bundle ID (app.front_bid)](https://xxtouch.app/en/docs/handbook/app/app.front_bid.md)
Path: handbook/app/app.front_bid.md

# Get foreground app bundle ID (app.front_bid)

## Declaration

```lua
bid = app.front_bid()
```

## Returns

- bid
  String. The bundle ID of the foreground app.
  Returns `"com.apple.springboard"` when no app is in the foreground but SpringBoard is already loaded.
  Returns `"com.apple.backboardd"` when no app is in the foreground and SpringBoard has not yet started (early boot stage).

## Description

- Get the bundle ID of the foreground app.

## Example

```lua
local bid = app.front_bid()
sys.alert("Foreground app bundle ID: "..bid)
```
Note: uses non-chapter API [`sys.alert`](/en/docs/handbook/sys/sys.alert.md).

---

Source: [Get device UDID (device.udid)](https://xxtouch.app/en/docs/handbook/device/device.udid.md)
Path: handbook/device/device.udid.md

# Get device UDID (device.udid)

## Declaration

```lua
udid = device.udid()
```

## Returns

- udid
  String. Device UDID

## Description

> UDID reference: [The iPhone Wiki – UDID](https://www.theiphonewiki.com/wiki/UDID)

## Example

```lua
sys.alert("UDID: " .. device.udid())
```
Note: Uses function outside this chapter [`sys.alert`](/en/docs/handbook/sys/sys.alert.md)

---

Source: [Add a checkbox group (:add_checkbox)](https://xxtouch.app/en/docs/handbook/dialog/dialogm_add_checkbox.md)
Path: handbook/dialog/dialogm_add_checkbox.md

# Add a checkbox group (:add_checkbox)

## Declaration

```lua
dialog_obj = dialog_obj:add_checkbox(label, options [, default_options])
```

## Parameters

- label
  String. The title text for the checkbox group
- options
  Table. Ordered list of option names in the group; names must be unique
- default_options
  Table, optional. Default selected option names. Default: {}

## Returns

- dialog_obj
  Dialog. Returns the dialog itself
- :show() return type
  Table. An ordered list containing all selected option names

## Description

> Add a checkbox group to the dialog

## Example

```lua
local c, s = dialog()
    :add_checkbox('A checkbox group', {'Option1', 'Option2', 'Option3', 'Option4'}, {'Option1', 'Option3'})
    :show()
print('Selected count: ' .. #(s['A checkbox group']))
print('Selected list:')
for _, oname in ipairs(s['A checkbox group']) do
    print(oname)
end
sys.alert(print.out())
```
Note: Uses functions outside this chapter [`sys.alert`](/en/docs/handbook/sys/sys.alert.md), [`print`](/en/docs/handbook/develop-helper/print.md), [`print.out`](/en/docs/handbook/develop-helper/print.out.md)

## Full example

See [:show()](/en/docs/handbook/dialog/dialogm_show.md)

---

Source: [Insert a sequence into file before a line (file.insert_lines)](https://xxtouch.app/en/docs/handbook/file/file.insert_lines.md)
Path: handbook/file/file.insert_lines.md

# Insert a sequence into file before a line (file.insert_lines)

## Declaration

```lua
ok, err = file.insert_lines(path, n, lines)
```

## Parameters

- path
  String. Absolute file path.
- n
  Integer. Line number. 0 means last line + 1. Negative means counting from the end.
- lines
  Array. Lines to insert.

## Returns

- ok
  Boolean. true if success, false if failure.
- err
  String. Error message when operation fails.

## Description

> Convert an array to lines and insert before the specified line. Creates file if it does not exist. Returns false if directory does not exist.
> This function automatically strips UTF-8 BOM at the file head.

## Example

```lua
local success = file.insert_lines("/var/mobile/1.txt", 0, { -- append to the end
    "The quick brown fox",
    "jumps over the lazy dog",
})
if success then
    sys.alert("Lines inserted successfully")
else
    sys.alert("Failed")
end
```
**Note**: Uses [`sys.alert`](/en/docs/handbook/sys/sys.alert.md)

---

Source: [Rotate image 90 degrees left (:turn_left)](https://xxtouch.app/en/docs/handbook/image/imagem_turn_left.md)
Path: handbook/image/imagem_turn_left.md

# Rotate image 90 degrees left (:turn_left)

## Declaration

```lua
img = img:turn_left()
```

## Returns

- img
  Image object. Returns the image object itself

## Description

> Rotate the image 90 degrees to the left
> Mutates the image in-place
> Performance: no data copy during operation

---

Source: [Check whether a hardware keyboard is connected (:is_connected)](https://xxtouch.app/en/docs/handbook/key/hardware_keyboardm_is_connected.md)
Path: handbook/key/hardware_keyboardm_is_connected.md

# Check whether a hardware keyboard is connected (:is_connected)

> **This method is available in versions after 20260805**

## Declaration

```lua
connected = keyboard:is_connected()
```

## Returns

- connected
  Boolean. Returns `true` while the object is connected and available for use, and `false` after disconnection.

## Description

> Get the connection state of the current hardware keyboard object.

After a global hardware keyboard is disconnected, Lua variables may still hold the original object, but this method returns `false` and [`key.get_global_keyboard`](key.get_global_keyboard.md) returns `nil`.

## Example

```lua
local keyboard = assert(key.connect_keyboard())

local connected = keyboard:is_connected()
local properties = keyboard:get_properties()
local success, err = keyboard:disconnect()
assert(success, err)
```

---

Source: [Run a transaction on process dict (proc_dict_run)](https://xxtouch.app/en/docs/handbook/proc/proc_dict_run.md)
Path: handbook/proc/proc_dict_run.md

# Run a transaction on process dict (proc_dict_run)

## Declaration

```lua
ret, err = proc_dict_run(tx_code)
```

## Parameters

- tx_code
  String. The Lua code to execute as a transaction.

## Returns

- ret
  String | nil. On success, returns the value returned by the code; on failure, returns nil.
- err
  String | nil. On success, returns nil; when code errors, returns error message.

## Description

- Available for versions after 20250427.
- All process queues whose names start with "xxtouch." or "1ferver." are reserved.
- Execute process-dict transaction code; during execution, other threads are blocked from calling proc_ functions.
- Maximum 1,000,000 lines per single run.
- If successful, the code may return a string value which will be returned to the caller. If the code returns nil, an empty string will be returned to the caller.
- On failure, returns nil and error message.

<details>

<summary>Allowed modules and functions in transaction Lua code</summary>

base (excluding require)
table
string
math
utf8
bit32
json
os.time()
os.clock()
sys.mtime()
utils.gen_uuid()
proc_put(key, value)
proc_get(key)
proc_queue_push_back(key, value)
proc_queue_push_front(key, value)
proc_queue_pop_front(key)
proc_queue_pop_back(key)
proc_queue_pop_value(key, value)
proc_queue_count_value(key, value)
proc_queue_clear(key)
proc_queue_read(key)
proc_queue_size(key)

</details>

## Example

```lua
function proc_inc(key, int_value)
    return proc_dict_run(string.format([[
        local key = %q
        local value = %d
        local ov = proc_get(key)
        if ov == '' then
            ov = 0
        else
            ov = tonumber(ov)
        end
        if not ov then
            error('not a number')
        end
        proc_put(key, tostring(ov + value))
        return ov
    ]], key, int_value))
end

for i = 1, 20 do
    nLog(proc_inc('haha', 10))
end
```

---

Source: [Inverse Rotate Coordinates (screen.unrotate_xy)](https://xxtouch.app/en/docs/handbook/screen/screen.unrotate_xy.md)
Path: handbook/screen/screen.unrotate_xy.md

# Inverse Rotate Coordinates (screen.unrotate_xy)

## Declaration

```lua
ux, uy = screen.unrotate_xy(x, y, original_rotation)
```

## Parameters

- x, y
  Integer. Coordinates to convert back to portrait.
- **original_rotation**
  0 = coordinates are portrait (Home at bottom); returns as-is
  1 = coordinates are landscape (Home at right)
  2 = coordinates are landscape (Home at left)
  3 = coordinates are portrait (Home at top)

## Returns

- ux, uy
  Integer. Portrait coordinates corresponding to the given **original_rotation** coordinates.

## Description

> Inverse rotate coordinates, typically used to convert landscape coordinates back to portrait: `init(original_rotation) -> init(0)`.
> **Requires software version 1.3.8 or later.**

## Example

```lua
rx, ry = screen.unrotate_xy(100, 200, 1) -- Convert landscape coordinates (100, 200) back to portrait
```

---

Source: [Send Signal to Processes by Name (sys.killall)](https://xxtouch.app/en/docs/handbook/sys/sys.killall.md)
Path: handbook/sys/sys.killall.md

# Send Signal to Processes by Name (sys.killall)

## Declaration

```lua
sys.killall(signal, [name1, name2, ...])
```

## Parameters

- signal
  Integer. Signal number.
- name1, name2, ...
  String. Process names. Optional. You can specify multiple process names.

## Description

> Sends a signal to processes by name.
> Available in versions after 2025-02-20.

## Examples

```lua
-- Respring device
sys.killall(9, "SpringBoard", "backboardd")
```

---

Source: [Capture a UI Snapshot (ui_element.snapshot)](https://xxtouch.app/en/docs/handbook/ui_element/ui_element.snapshot.md)
Path: handbook/ui_element/ui_element.snapshot.md

# Capture a UI Snapshot (ui_element.snapshot)

> **This function is available in versions after 20260507**

## Declaration

```lua
snapshot, err = ui_element.snapshot([ options ])
```

## Parameters

- options
  Optional, table. See [Common options](options.md).

[Attribute exclusion options](options.md#attribute-exclusions) are supported **from 20261115**.

## Returns

- snapshot
  Table. Current UI element list with snapshot methods. `nil` on failure.
- err
  String. Failure reason.

## Snapshot Methods

```lua
element = snapshot:find(selector)
elements = snapshot:find_all(selector)
ok, info = snapshot:click(selector_or_element [, options ])
ok, info = snapshot:scroll([ selector_or_element, ] direction [, options ])
ok, info = snapshot:input_text(selector_or_element, text [, options ])
ok, info = snapshot:set_text(selector_or_element, text [, options ])
ok, info = snapshot:clear_text(selector_or_element [, options ])
ok, info = snapshot:toggle(selector_or_element [, options ])
ok, info = snapshot:set_checked(selector_or_element, checked [, options ])
ok, info = snapshot:set_value(selector_or_element, value [, options ])
ok, info = snapshot:increase(selector_or_element [, options ])
ok, info = snapshot:decrease(selector_or_element [, options ])
```

## Description

> A snapshot is a one-time result, useful for repeated lookups or continuous actions on the same screen.
> After navigation, popups, scrolling, or content refresh, call `snapshot()` again.
> Common snapshot fields include `elements` and `count`.

## Example

```lua
local ui_element = require("ui_element")

local ui, err = ui_element.snapshot({
    max_level = 2,
})

if ui then
    local search = ui:find({
        title = "Search",
        role = "text_field",
    })
    if search then
        ui:set_text(search, "XXTouch")
    end
else
    sys.toast(err)
end
```

**Note**: Uses non-chapter API [`sys.toast`](/en/docs/handbook/sys/sys.toast.md).

---

Source: [RFC 3339 String to Timestamp (utils.date_from_rfc3339)](https://xxtouch.app/en/docs/handbook/utils/utils.date_from_rfc3339.md)
Path: handbook/utils/utils.date_from_rfc3339.md

# RFC 3339 String to Timestamp (utils.date_from_rfc3339)

## Declaration

```lua
ts = utils.date_from_rfc3339(rfc3339)
```

## Parameters

- rfc3339
  String. RFC 3339 formatted time string.

## Returns

- ts
  Number. Unix timestamp.

## Description

> Available after 2025-02-20.

## Examples

```lua
nLog(utils.date_from_rfc3339("2025-06-09T17:40:00.000Z")) -- 1749490800.0
```

---

Source: [Get foreground app pid (app.front_pid)](https://xxtouch.app/en/docs/handbook/app/app.front_pid.md)
Path: handbook/app/app.front_pid.md

# Get foreground app pid (app.front_pid)

## Declaration

```lua
pid = app.front_pid()
```

## Returns

- pid
  Integer. The pid of the foreground app, or 0 if no app is in the foreground.

## Description

- Get the pid of the foreground app.
- Returns 0 when no app is in the foreground (not the SpringBoard pid).
- If you need the SpringBoard pid, use:
```lua
local desktop_pid = app.pid_for_bid('com.apple.springboard')
sys.alert("SpringBoard pid: "..desktop_pid)
```

## Example

```lua
local pid = app.front_pid()
sys.alert("Foreground app pid: "..pid)
```
Note: uses non-chapter API [`sys.alert`](/en/docs/handbook/sys/sys.alert.md).

---

Source: [Get device serial number (device.serial_number)](https://xxtouch.app/en/docs/handbook/device/device.serial_number.md)
Path: handbook/device/device.serial_number.md

# Get device serial number (device.serial_number)

## Declaration

```lua
sn = device.serial_number()
```

## Returns

- sn
  String. Device serial number

## Example

```lua
sys.alert("Serial number: " .. device.serial_number())
```
Note: Uses function outside this chapter [`sys.alert`](/en/docs/handbook/sys/sys.alert.md)

---

Source: [Add a numeric range picker (:add_range)](https://xxtouch.app/en/docs/handbook/dialog/dialogm_add_range.md)
Path: handbook/dialog/dialogm_add_range.md

# Add a numeric range picker (:add_range)

## Declaration

```lua
dialog_obj = dialog_obj:add_range(label, range_params [, default_value])
```

## Parameters

- label
  String. Title text for the range picker
- range_params
  Table. Describes the range and step, in the form `{min, max, step}`
  - min
    Number. The leftmost value of the slider
  - max
    Number. The rightmost value of the slider
  - step
    Number, optional. Minimum increment when dragging. Default: 1
- default_value
  Number, optional. Default value. Default: min

## Returns

- dialog_obj
  Dialog. Returns the dialog itself
- :show() return type
  Number. The selected number

## Description

> Add a numeric range picker to the dialog

## Example

```lua
local c, s = dialog():add_range('A number', {222, 666, 1}, 333):show()
sys.alert('Value: ' .. s['A number'])
```
Note: Uses function outside this chapter [`sys.alert`](/en/docs/handbook/sys/sys.alert.md)

## Full example

See [:show()](/en/docs/handbook/dialog/dialogm_show.md)

---

Source: [Get file MD5 (file.md5)](https://xxtouch.app/en/docs/handbook/file/file.md5.md)
Path: handbook/file/file.md5.md

# Get file MD5 (file.md5)

## Declaration

```lua
md5, err = file.md5(path)
```

## Parameters

- path
  String. Absolute file path.

## Returns

- md5
  String or nil. nil if file does not exist or path is a directory; otherwise the file MD5 value.
- err
  String. Error message when operation fails.

## Description

> Get the MD5 value of a file.

## Example

```lua
local md5, err = file.md5("/var/mobile/1.zip")
if md5 then
    sys.alert("/var/mobile/1.zip MD5: "..md5)
else
    sys.alert("/var/mobile/1.zip is not a file: "..err)
end
```
**Note**: Uses [`sys.alert`](/en/docs/handbook/sys/sys.alert.md)

---

Source: [Rotate image 90 degrees right (:turn_right)](https://xxtouch.app/en/docs/handbook/image/imagem_turn_right.md)
Path: handbook/image/imagem_turn_right.md

# Rotate image 90 degrees right (:turn_right)

## Declaration

```lua
img = img:turn_right()
```

## Returns

- img
  Image object. Returns the image object itself

## Description

> Rotate the image 90 degrees to the right
> Mutates the image in-place
> Performance: no data copy during operation

---

Source: [Get hardware keyboard properties (:get_properties)](https://xxtouch.app/en/docs/handbook/key/hardware_keyboardm_get_properties.md)
Path: handbook/key/hardware_keyboardm_get_properties.md

# Get hardware keyboard properties (:get_properties)

> **This method is available in versions after 20260805**

## Declaration

```lua
properties = keyboard:get_properties()
```

## Returns

- properties
  Table. A copy of the configuration properties saved when the device was created.

## Description

> `get_properties()` returns the configuration saved at creation time, which may include system-managed properties. This is not live system state, and the values ultimately used by iOS may differ.

## Example

```lua
local keyboard = assert(key.connect_keyboard())

local properties = keyboard:get_properties()
print(properties.Product)
print(properties.Transport)

assert(keyboard:disconnect())
```

---

Source: [Recursively Change Owner (sys.lchown_r)](https://xxtouch.app/en/docs/handbook/sys/sys.lchown_r.md)
Path: handbook/sys/sys.lchown_r.md

# Recursively Change Owner (sys.lchown_r)

## Declaration

```lua
sys.lchown_r(path, uid, gid)
```

## Parameters

- path
  String.
- uid
  Integer.
- gid
  Integer.

## Description

> Recursively change owner for all files and subdirectories. Does not traverse deep directories pointed to by symlinks.
> Available in versions after 2025-02-20.

## Examples

```lua
sys.lchown_r("/var/mobile/Media/1ferver", 501, 501)
```

---

Source: [Timestamp to Formatted Date String (utils.date_to_format)](https://xxtouch.app/en/docs/handbook/utils/utils.date_to_format.md)
Path: handbook/utils/utils.date_to_format.md

# Timestamp to Formatted Date String (utils.date_to_format)

## Declaration

```lua
date = utils.date_to_format(format, timestamp[, options])
```

## Parameters

- format
  String. Date format.
- timestamp
  Number. Unix timestamp.
- options
  Table. Options.
  ```lua
  {
      tz = "GMT";       -- Timezone. Optional. Default: system timezone. See https://en.wikipedia.org/wiki/List_of_tz_database_time_zones
      locale = "en-US"; -- Locale. Optional. Default: the device's locale.
  }
  ```

## Returns

- date
  String. Formatted date string.

## Description

> Available after 2025-02-20.

## Format Reference

See: [Unicode Date Field Symbol Table](https://www.unicode.org/reports/tr35/tr35-dates.html#Date_Field_Symbol_Table)

| Category | Token | Example | Description |
| :--- | :--- | :--- | :--- |
| Year | `yyyy` | `2024` | 4-digit year |
|  | `yy` | `24` | 2-digit year |
| Month | `MMMM` | `July` | Full month name |
|  | `MMM` | `Jul` | Abbreviated month |
|  | `MM` | `07` | 2-digit month |
|  | `M` | `7` | 1-2 digit month |
| Day | `dd` | `06` | 2-digit day |
|  | `d` | `6` | 1-2 digit day |
| Weekday | `EEEE` | `Saturday` | Full name |
|  | `E`, `EE`, `EEE` | `Sat` | Abbreviation |
|  | `e`, `ee` | `7` | Localized weekday number (Sun=1, Sat=7) |
| Hour | `HH` | `15` | 24h two-digit |
|  | `H` | `15` | 24h 1-2 digit |
|  | `hh` | `03` | 12h two-digit |
|  | `h` | `3` | 12h 1-2 digit |
|  | `a` | `PM` | AM/PM |
| Minute | `mm` | `05` | Two-digit minute |
|  | `m` | `5` | 1-2 digit minute |
| Second | `ss` | `09` | Two-digit second |
|  | `S` | `.1` `.12` `.123` | Milliseconds; count of S sets decimals |
| Timezone | `zzzz` | `Pacific Daylight Time` | Full name |
|  | `zzz`, `z` | `PDT` | Abbreviation |
|  | `ZZZZZ` | `-07:00` | ISO 8601 offset with colon |
|  | `Z`, `ZZ`, `ZZZ` | `-0700` | RFC 822 offset |

## Examples

```lua
nLog(utils.date_to_format("EEE, dd MMM yyyy HH:mm:ss ZZZZ", 1749490800, {tz = "PST"; locale = 'en-US'}))
nLog(utils.date_to_format("EEE, dd MMM yyyy HH:mm:ss ZZZZ", 1749490800, {tz = "PST"; locale = 'zh-CN'}))
```

---

Source: [Open a URL in foreground (app.open_url)](https://xxtouch.app/en/docs/handbook/app/app.open_url.md)
Path: handbook/app/app.open_url.md

# Open a URL in foreground (app.open_url)

## Declaration

```lua
ok = app.open_url(URL)
```

## Parameters

- URL
  String. The URL to open. Can open [URL Scheme](https://developer.apple.com/library/ios/featuredarticles/iPhoneURLScheme_Reference/Introduction/Introduction.html) (see [URL Scheme usage](/en/docs/handbook/supplement/url-scheme.md)).

## Returns

- ok
  Boolean. Whether the URL was opened successfully.

## Description

- Open a URL in the foreground. Can open [URL Scheme](https://developer.apple.com/library/ios/featuredarticles/iPhoneURLScheme_Reference/Introduction/Introduction.html) (see [URL Scheme usage](/en/docs/handbook/supplement/url-scheme.md)).
- For some URLs, this API may not give the desired behavior. In a jailbreak environment you can try the `uiopen` shell command instead:
```lua
local function sh_escape(path) -- XXTouch built-in function; free for commercial use
    path = string.gsub(path, "([ \\()<>\'\"`#&*;?~$|])", "\\%1")
    return path
end
os.execute('uiopen '..sh_escape('https://www.google.com'))
os.execute('uiopen '..sh_escape('prefs:root=SAFARI&path=CLEAR_HISTORY_AND_DATA'))
```

## Example

```lua
app.open_url("https://www.google.com") -- open Google's homepage in Safari
--
app.open_url("prefs:root=SAFARI&path=CLEAR_HISTORY_AND_DATA") -- Settings -> Safari -> Clear History and Website Data
```

---

Source: [Get Wi‑Fi MAC address (device.wifi_mac)](https://xxtouch.app/en/docs/handbook/device/device.wifi_mac.md)
Path: handbook/device/device.wifi_mac.md

# Get Wi‑Fi MAC address (device.wifi_mac)

## Declaration

```lua
mac = device.wifi_mac()
```

## Returns

- mac
  String. Device Wi‑Fi MAC address

## Example

```lua
sys.alert("Wi‑Fi MAC: " .. device.wifi_mac())
```
Note: Uses function outside this chapter [`sys.alert`](/en/docs/handbook/sys/sys.alert.md)

---

Source: [! Present dialog and return user selection (:show)](https://xxtouch.app/en/docs/handbook/dialog/dialogm_show.md)
Path: handbook/dialog/dialogm_show.md

# ! Present dialog and return user selection (:show)

## Declaration

```lua
confirmed, selections = dlg:show()
```

## Returns

- confirmed
  Boolean. Whether the Submit button was pressed. Returns false on timeout or when closed by the “×”.
- selections
  Table. A key-value table mapped by option labels.

## Description

> Present the dialog and return the user's selections.
> If configuration saving is enabled via `:set_config(name)`, pressing **Submit** saves the config; closing with “×” or timing out does not.

## Simple example

```lua
local c, s = dialog():add_switch('A switch', false):show()
sys.alert(s['A switch'])
```
**Note**: Uses [`sys.alert`](/en/docs/handbook/sys/sys.alert.md)

## Complex example

```lua
local dlg = dialog() -- create dialog object
--
-- configure dialog
dlg:set_config('test') -- config storage ID
dlg:set_timeout(30)
dlg:add_label('Simple demo')
dlg:add_range('HP', {0, 1000, 1}, 300)
dlg:add_input('Account', 'ccc')
dlg:add_input('Password', 'aaaa')
dlg:add_picker('Gender', {'Male', 'Female', 'Unknown'}, 'Male')
dlg:add_switch('Enable debug mode', false)
dlg:add_checkbox('Favorite games', {'Overwatch', 'World of Warcraft', 'Hearthstone'}, {'Overwatch', 'World of Warcraft'})
dlg:add_radio('Most favorite game', {'Overwatch', 'World of Warcraft', 'Hearthstone'}, 'World of Warcraft')
--
local confirm, selects = dlg:show() -- present and get result
--
if (confirm) then
    print("You pressed Submit")
else
    print("You did not press Submit")
end
--
print("Account", selects["Account"])
print("Password", selects["Password"])
print("Gender", selects["Gender"])
print("HP", selects["HP"])
--
if (selects['Enable debug mode']) then
    print("Debug mode is enabled")
else
    print("Debug mode is disabled")
end
--
print("Your favorite games")
for _, gamename in ipairs(selects['Favorite games']) do
    print(gamename)
end
--
print("Your most favorite game:"..selects["Most favorite game"])
--
sys.alert(print.out())
```
**Note**: Uses [`sys.alert`](/en/docs/handbook/sys/sys.alert.md), [`print`](/en/docs/handbook/develop-helper/print.md), [`print.out`](/en/docs/handbook/develop-helper/print.out.md)

---

Source: [Get file SHA1 (file.sha1)](https://xxtouch.app/en/docs/handbook/file/file.sha1.md)
Path: handbook/file/file.sha1.md

# Get file SHA1 (file.sha1)

## Declaration

```lua
sha1, err = file.sha1(path)
```

## Parameters

- path
  String. Absolute file path.

## Returns

- sha1
  String or nil. nil if file does not exist or path is a directory; otherwise the file SHA1 value.
- err
  String. Error message when operation fails.

## Description

> Get the SHA1 value of a file.

## Example

```lua
local sha1, err = file.sha1("/var/mobile/1.zip")
if sha1 then
    sys.alert("/var/mobile/1.zip SHA1: "..sha1)
else
    sys.alert("/var/mobile/1.zip is not a file: "..err)
end
```
**Note**: Uses [`sys.alert`](/en/docs/handbook/sys/sys.alert.md)

---

Source: [Get image size (:size)](https://xxtouch.app/en/docs/handbook/image/imagem_size.md)
Path: handbook/image/imagem_size.md

# Get image size (:size)

## Declaration

```lua
w, h = img:size()
```

## Returns

- w, h
  Integer. Width and height of the image object

## Description

> Get width and height of the image object. Note that width may not be less than height; rotation can change dimensions

## Example

```lua
local img = image.load_file("/var/mobile/1.png")
local w, h = img:size()
sys.alert("Width: "..w.."\nHeight: "..h)
```

---

Source: [Disconnect a hardware keyboard (:disconnect)](https://xxtouch.app/en/docs/handbook/key/hardware_keyboardm_disconnect.md)
Path: handbook/key/hardware_keyboardm_disconnect.md

# Disconnect a hardware keyboard (:disconnect)

> **This method is available in versions after 20260805**

## Declaration

```lua
success, err = keyboard:disconnect()
```

## Returns

- success
  Boolean. Returns `true` after successful disconnection and `false` on failure.
- err
  String. Error message returned when disconnection fails.

## Description

> Releases all keys and disconnects this hardware keyboard object.

- This method may be called repeatedly.
- If the object is the current global hardware keyboard, this method also clears the global keyboard connection.
- If the same hardware keyboard is running a `:press` or `:send_text` sequence, this method returns `false, "hardware keyboard is busy"`.
- When Lua collects a hardware keyboard object or the script stops, XXTouch also releases all keys and disconnects the object.

## Example

```lua
local keyboard = assert(key.connect_keyboard())

local success, err = keyboard:disconnect()
assert(success, err)
```

---

Source: [Recursively Change Mode (sys.lchmod_r)](https://xxtouch.app/en/docs/handbook/sys/sys.lchmod_r.md)
Path: handbook/sys/sys.lchmod_r.md

# Recursively Change Mode (sys.lchmod_r)

## Declaration

```lua
sys.lchmod_r(path, mode)
```

## Parameters

- path
  String.
- mode
  Integer. Permission bits, e.g. octal `0755` equals `7 * 8^2 | 5 * 8^1 | 5`.
  String. Permission text, e.g. `"0755"` or `"rwxr-xr-x"` (supported since 2025-06-25).

## Description

> Recursively change mode for all files and subdirectories. Does not traverse deep directories pointed to by symlinks.
> Available in versions after 2025-02-20.

## Examples

```lua
sys.lchmod_r("/var/mobile/Media/1ferver", 7 * 8^2 | 5 * 8^1 | 5)

-- Since 2025-06-25 the following forms are also supported
sys.lchmod_r("/var/mobile/Media/1ferver", "0755")
sys.lchmod_r("/var/mobile/Media/1ferver", "rwxr-xr-x")
```

---

Source: [Formatted Date String to Timestamp (utils.date_from_format)](https://xxtouch.app/en/docs/handbook/utils/utils.date_from_format.md)
Path: handbook/utils/utils.date_from_format.md

# Formatted Date String to Timestamp (utils.date_from_format)

## Declaration

```lua
timestamp = utils.date_from_format(format, date[, options])
```

## Parameters

- format
  String. Date format.
- date
  String. Date string.
- options
  Table. Options.
  ```lua
  {
      tz = "GMT";       -- Timezone. Optional. Default: system timezone. See https://en.wikipedia.org/wiki/List_of_tz_database_time_zones
      locale = "en-US"; -- Locale. Optional. Default: the device's locale.
  }
  ```

## Returns

- timestamp
  Number. Unix timestamp.

## Description

> Available after 2025-02-20.

## Format Reference

[Unicode Date Field Symbol Table](https://www.unicode.org/reports/tr35/tr35-dates.html#Date_Field_Symbol_Table)

| Category | Token | Example | Description |
| :--- | :--- | :--- | :--- |
| Year | `yyyy` | `2024` | 4-digit year |
|  | `yy` | `24` | 2-digit year |
| Month | `MMMM` | `July` | Full month name |
|  | `MMM` | `Jul` | Abbreviated month |
|  | `MM` | `07` | 2-digit month (01-12) |
|  | `M` | `7` | 1-2 digit month |
| Day | `dd` | `06` | 2-digit day (01-31) |
|  | `d` | `6` | 1-2 digit day |
| Day of Week | `EEEE` | `Saturday` | Full name |
|  | `E`, `EE`, `EEE` | `Sat` | Abbreviation |
|  | `e`, `ee` | `7` | Localized weekday number (Sun=1, Sat=7) |
| Hour | `HH` | `15` | 24h two-digit (00-23) |
|  | `H` | `15` | 24h 1-2 digit |
|  | `hh` | `03` | 12h two-digit (01-12) |
|  | `h` | `3` | 12h 1-2 digit |
|  | `a` | `PM` | AM/PM |
| Minute | `mm` | `05` | Two-digit minute (00-59) |
|  | `m` | `5` | 1-2 digit minute |
| Second | `ss` | `09` | Two-digit second (00-59) |
|  | `S` | `.1` `.12` `.123` | Milliseconds; count of S sets decimals |
| Time Zone | `zzzz` | `Pacific Daylight Time` | Full name |
|  | `zzz`, `z` | `PDT` | Abbreviation |
|  | `ZZZZZ` | `-07:00` | ISO 8601 offset with colon |
|  | `Z`, `ZZ`, `ZZZ` | `-0700` | RFC 822 offset |

## Examples

```lua
nLog(utils.date_from_format("EEE, dd MMM yyyy HH:mm:ss ZZZZ", "Mon, 09 Jun 2025 17:40:00 GMT", {tz = "GMT"; locale = 'en-US'})) -- 1749490800.0
```

---

Source: [List all app bundle ids (app.bundles)](https://xxtouch.app/en/docs/handbook/app/app.bundles.md)
Path: handbook/app/app.bundles.md

# List all app bundle ids (app.bundles)

## Declaration

```lua
bids = app.bundles()
```

## Returns

- bids
  Array (sequential table). All app bundle identifiers on the device, including system apps.

## Description

- Get the list of all app bundle identifiers on the device.

## Example

```lua
-- Iterate and close all apps
for _, bid in ipairs(app.bundles()) do
    app.close(bid)
end
```

---

Source: [Get current Wi‑Fi info (device.wifi_info)](https://xxtouch.app/en/docs/handbook/device/device.wifi_info.md)
Path: handbook/device/device.wifi_info.md

# Get current Wi‑Fi info (device.wifi_info)

## Declaration

```lua
info = device.wifi_info()
```

## Returns

- info
  Table | nil. On success returns a table; nil on failure
  <details>
  <summary>Structure</summary>

  ```lua
  {
      SSID = string_value,
      BSSID = string_value,
      hidden = boolean_value,
      encryption = string_value,
      password = string_value,
      channel = integer_value,
  }
  ```
  </details>

## Description

> Available in app version >= 1.3.8

## Example

```lua
nLog(device.wifi_info())
```

---

Source: [! Load dialog configuration without presenting (:load)](https://xxtouch.app/en/docs/handbook/dialog/dialogm_load.md)
Path: handbook/dialog/dialogm_load.md

# ! Load dialog configuration without presenting (:load)

## Declaration

```lua
confirmed, selections = dlg:load()
```

## Returns

- confirmed
  Boolean. Kept for compatibility with `:show`'s return shape; this method always returns false.
- selections
  Table. A key-value table mapped by option labels.

## Description

> Load the dialog configuration without presenting it. If there is no saved configuration, default values are loaded.

## Example

```lua
local dlg = dialog()
--
dlg:set_config('test')
dlg:set_timeout(30)
dlg:add_label('Simple demo')
dlg:add_range('HP', {0, 1000, 1}, 300)
dlg:add_input('Account', 'ccc')
dlg:add_input('Password', 'aaaa')
dlg:add_picker('Gender', {'Male', 'Female', 'Unknown'}, 'Male')
dlg:add_switch('Enable debug mode', false)
dlg:add_checkbox('Favorite games', {'Overwatch', 'World of Warcraft', 'Hearthstone'}, {'Overwatch', 'World of Warcraft'})
dlg:add_radio('Most favorite game', {'Overwatch', 'World of Warcraft', 'Hearthstone'}, 'World of Warcraft')
--
local _, selects
--
if (utils.is_launch_via_app()) then
    _, selects = dlg:show()         -- show when launched from the app
else
    _, selects = dlg:load()         -- otherwise do not present
end
--
print("Account", selects["Account"])
print("Password", selects["Password"])
print("Gender", selects["Gender"])
print("HP", selects["HP"])
--
if (selects['Enable debug mode']) then
    print("Debug mode is enabled")
else
    print("Debug mode is disabled")
end
--
print("Your favorite games")
for _, gamename in ipairs(selects['Favorite games']) do
    print(gamename)
end
--
print("Your most favorite game:"..selects["Most favorite game"])
--
sys.alert(print.out())
```
**Note**: Uses [`utils.is_launch_via_app`](/en/docs/handbook/utils/utils.is_launch_via_app.md), [`sys.alert`](/en/docs/handbook/sys/sys.alert.md), [`print`](/en/docs/handbook/develop-helper/print.md), [`print.out`](/en/docs/handbook/develop-helper/print.out.md)

---

Source: [Remove file or directory (file.remove)](https://xxtouch.app/en/docs/handbook/file/file.remove.md)
Path: handbook/file/file.remove.md

# Remove file or directory (file.remove)

## Declaration

```lua
ok, err = file.remove(path)
```

## Parameters

- path
  String. Absolute file path.

## Returns

- ok
  Boolean. true if success, false if failure.
- err
  String. Error message when operation fails.

## Description

> Remove a file or directory.
> Keywords: delete file, file deletion, delete directory.
> **This function is available only in versions released after 2025-03-13.**

## Example

```lua
ok, err = file.remove(XXT_SCRIPTS_PATH.."/1.zip")
if not ok then
    sys.alert("Remove failed: "..err)
end
```
**Note**: Uses [`sys.alert`](/en/docs/handbook/sys/sys.alert.md)

---

Source: [Get the color of a pixel (:get_color)](https://xxtouch.app/en/docs/handbook/image/imagem_get_color.md)
Path: handbook/image/imagem_get_color.md

# Get the color of a pixel (:get_color)

## Declaration

```lua
color, alpha = img:get_color(x, y)
```

## Parameters

- x, y
  Integer. Coordinates of the pixel in the current image

## Returns

- color
  Integer. Color value of the pixel. Note: if alpha is not 255, the RGB value should consider division by opacity (alpha/255)
- alpha
  Integer. Opacity of the pixel, range 0~255

## Description

> Get the color of a pixel in an image. Unlike screen sampling, image pixels also have an alpha channel

## Example

```lua
local img = image.load_file("/var/mobile/1.png")
local clr = img:get_color(100, 100)
sys.alert(string.format("Color at (100, 100): 0x%06x", clr))
```

---

Source: [Recursively Change Owner and Mode (sys.lchownmod_r)](https://xxtouch.app/en/docs/handbook/sys/sys.lchownmod_r.md)
Path: handbook/sys/sys.lchownmod_r.md

# Recursively Change Owner and Mode (sys.lchownmod_r)

## Declaration

```lua
sys.lchownmod_r(path, uid, gid, mode)
```

## Parameters

- path
  String.
- uid
  Integer.
- gid
  Integer.
- mode
  Integer. Permission bits, e.g. octal o0755 = `7 * 8^2 | 5 * 8^1 | 5`.
  String. Permission text, e.g. "0755" or "rwxr-xr-x" (supported since 2025-06-25).

## Description

> Recursively change owner and mode for all files and subdirectories. Does not traverse deep directories pointed to by symlinks.
> **Available in versions after 2025-02-20.**

## Examples

```lua
sys.lchownmod_r("/var/mobile/Media/1ferver", 501, 501, 7 * 8^2 | 5 * 8^1 | 5)

-- Since 2025-06-25 the following forms are also supported
sys.lchownmod_r("/var/mobile/Media/1ferver", 501, 501, "0755")
sys.lchownmod_r("/var/mobile/Media/1ferver", 501, 501, "rwxr-xr-x")
```

---

Source: [Get current process list (app.all_procs)](https://xxtouch.app/en/docs/handbook/app/app.all_procs.md)
Path: handbook/app/app.all_procs.md

# Get current process list (app.all_procs)

## Declaration

```lua
procs = app.all_procs()
```

## Returns

- procs
  Array (sequential table). The process list.

  <details>
  <summary>Process list structure</summary>

  ```lua
  {
      {pid = pid1, name = name1},
      {pid = pid2, name = name2},
      ...
  }
  ```
  </details>

## Description

- The function does not guarantee that the full process name is available.

## Example

```lua
proc_list = app.all_procs()
```

---

Source: [Get all interface IPs (device.ifaddrs)](https://xxtouch.app/en/docs/handbook/device/device.ifaddrs.md)
Path: handbook/device/device.ifaddrs.md

# Get all interface IPs (device.ifaddrs)

## Declaration

```lua
infos = device.ifaddrs()
```

## Returns

- infos
  Array | nil. On success returns a table with structure below; nil on failure
  <details>
  <summary>Structure</summary>

  ```lua
  {
      {"ifname1", "ip1"},
      {"ifname2", "ip2"},
      ...
  }
  ```
  </details>

## Description

> Get all interface IPs of the device

## Example

```lua
-- Get Wi-Fi IP
local ip = "Wi-Fi is off"
for i, v in ipairs(device.ifaddrs()) do
    if (v[1] == "en0") then
        ip = v[2]
    end
end
sys.alert(ip)
```
Note: Uses function outside this chapter [`sys.alert`](/en/docs/handbook/sys/sys.alert.md)

---

Source: [Move file or directory (file.move)](https://xxtouch.app/en/docs/handbook/file/file.move.md)
Path: handbook/file/file.move.md

# Move file or directory (file.move)


## Declaration

```lua
ok, err = file.move(src, dst [, mode])
```


## Parameters

- src
    String. Absolute path of the source file or directory.
- dst
    String. Complete absolute path of the resulting file or directory, including the destination file or directory name.
- mode 20250914+
    String, optional. Move mode. Values:
    - Empty string or omitted: default mode (no-clobber); fail if the destination already exists.
    - "overwrite" or "o": overwrite mode; replace the existing destination (the existing destination will be deleted).
    - "merge" or "m": merge mode (directories only); keep files already in the destination.
    - "overwrite-merge" or "om"/"mo": overwrite-merge mode; merge directories and overwrite files with the same name.

## Returns

- ok
    Boolean. true on success, false on failure.
- err
    String. Error message when the operation fails.


## Description

> Move the file or directory at `src` as `dst`; changing its name within the same directory renames it.
> **This function means “move as”, not “move into”.** `dst` specifies the final file or directory; the source file or directory name is not appended automatically. Even if the destination is an existing directory or its path ends in `/`, the source file or directory will not be placed inside it.
> For example, to move `/a/b/c` into `/d/e/` and keep the name `c`, specify `/d/e/c` as the destination, not just `/d/e/`.
> If the destination already exists, the `mode` parameter determines what happens: the default mode fails, overwrite mode replaces the destination itself, and directory merge modes merge the source directory contents into the destination directory.
> Keywords: rename file, rename directory, rename folder, move file, move directory, move folder.
> **This function is available only in versions released after 20250313.**


## Example

```lua
ok, err = file.move(XXT_SCRIPTS_PATH..'/1.zip', XXT_SCRIPTS_PATH..'/2.zip')
if not ok then
    sys.alert('Move failed: '..err)
end
```
**Note**: The code above uses [`sys.alert`](../sys/sys.alert.md), a function outside this chapter.

### Move to another directory and keep the name

```lua
-- Assume /d/e is an existing directory and /d/e/c does not yet exist
file.move('/a/b/c', '/d/e/c') -- Correct: move c as /d/e/c

-- The following is an independent example of an incorrect call: the target is e itself, not c inside e
-- file.move('/a/b/c', '/d/e/') -- Default mode fails because the destination already exists

-- Overwrite mode replaces e itself; it does not create /d/e/c (20250914+)
-- file.move('/a/b/c', '/d/e/', 'overwrite')
```

### Wrap a “move into directory” function

The following custom wrapper requires a version released after 20250914. The destination directory must already exist. The function keeps the source file or directory name and passes the optional `mode` parameter to `file.move`. Conflicts with an existing name are still handled according to the specified mode.

```lua
local function file_move_into(src_path, dst_dir, mode)
    if file.exists(dst_dir) ~= "directory" then
        return false, "Target is not a directory"
    end

    local name, err = file.path.last_component(src_path)
    if not name then
        return false, err
    end
    -- Avoid using the destination directory itself or its parent as the final target.
    if name == "" or name == "/" or name == "." or name == ".." then
        return false, "Source path must end with a file or directory name"
    end

    local dst_path, path_err = file.path.add_component(dst_dir, name)
    if not dst_path then
        return false, path_err
    end
    return file.move(src_path, dst_path, mode)
end

-- Assume /d/e is an existing directory; move c as /d/e/c
local ok, err = file_move_into("/a/b/c", "/d/e/")
if not ok then
    print("Move failed: "..err)
end

-- To replace /d/e/c, specify overwrite mode when calling the function:
-- file_move_into("/a/b/c", "/d/e/", "overwrite")
```

**Note**: The code above uses [`file.exists`](file.exists.md), [`file.path.last_component`](file.path.last_component.md), and [`file.path.add_component`](file.path.add_component.md).

---

Source: [Set the color of a pixel (:set_color)](https://xxtouch.app/en/docs/handbook/image/imagem_set_color.md)
Path: handbook/image/imagem_set_color.md

# Set the color of a pixel (:set_color)

## Declaration

```lua
img = img:set_color(x, y, color)
```

## Parameters

- x, y
  Integer. Coordinates of the pixel in the current image
- color
  Integer. Color value to set

## Returns

- img
  Image object. Returns the image object itself after setting the color

## Description

> Set the color of a pixel in an image
> Mutates the image in-place
> Performance: no data copy during operation

---

Source: [Recursively Create Directory (sys.mkdir_p)](https://xxtouch.app/en/docs/handbook/sys/sys.mkdir_p.md)
Path: handbook/sys/sys.mkdir_p.md

# Recursively Create Directory (sys.mkdir_p)

## Declaration

```lua
sys.mkdir_p(dir)
```

## Parameters

- dir
  String.

## Description

> Recursively create directories. Newly created directories have owner UID/GID 501 and permission octal `0777`.
> **Available in versions after 2025-02-20.**

## Examples

```lua
sys.mkdir_p("/var/mobile/Media/1ferver/lua/scripts/a/b/c/d")
```

---

Source: [Set app TCC permissions (app.set_tcc)](https://xxtouch.app/en/docs/handbook/app/app.set_tcc.md)
Path: handbook/app/app.set_tcc.md

# Set app TCC permissions (app.set_tcc)

## Declaration

```lua
ok, old_value = app.set_tcc(bid, service, value)
```

## Parameters

- bid
  String. App bundle identifier. You can find it in `XXT App -> More -> App List`.
- service
  String.
  <details>

  <summary>TCC service identifiers</summary>

  ```lua
  kTCCServiceAccessibility
  kTCCServiceAddressBook
  kTCCServiceAppleEvents
  kTCCServiceCalendar
  kTCCServiceCamera
  kTCCServiceContactsFull
  kTCCServiceContactsLimited
  kTCCServiceDeveloperTool
  kTCCServiceFacebook
  kTCCServiceLinkedIn
  kTCCServiceListenEvent
  kTCCServiceLiverpool
  kTCCServiceLocation
  kTCCServiceMediaLibrary
  kTCCServiceMicrophone
  kTCCServiceMotion
  kTCCServicePhotos
  kTCCServicePhotosAdd
  kTCCServicePostEvent
  kTCCServiceReminders
  kTCCServiceScreenCapture
  kTCCServiceShareKit
  kTCCServiceSinaWeibo
  kTCCServiceSiri
  kTCCServiceSpeechRecognition
  kTCCServiceSystemPolicyAllFiles
  kTCCServiceSystemPolicyDesktopFolder
  kTCCServiceSystemPolicyDeveloperFiles
  kTCCServiceSystemPolicyDocumentsFolder
  kTCCServiceSystemPolicyDownloadsFolder
  kTCCServiceSystemPolicyNetworkVolumes
  kTCCServiceSystemPolicyRemovableVolumes
  kTCCServiceSystemPolicySysAdminFiles
  kTCCServiceTencentWeibo
  kTCCServiceTwitter
  kTCCServiceUbiquity
  kTCCServiceWillow
  kTCCServicePasteboard
  kTCCServiceUserTracking
  ```
  </details>
- value
  Integer. Set `value` to `-1` to delete TCC permissions for the given `bid`.

## Returns

- ok
  Boolean. Whether the operation succeeded.
- old_value
  Integer. Returns -1 if the app did not have this permission previously.

## Description

- Requires software version 1.3.8 or later.

## Example

```lua
app.set_tcc("com.apple.SafariViewService", "kTCCServicePasteboard", 2)
```

---

Source: [Get current battery level (device.battery_level)](https://xxtouch.app/en/docs/handbook/device/device.battery_level.md)
Path: handbook/device/device.battery_level.md

# Get current battery level (device.battery_level)

## Declaration

```lua
level = device.battery_level()
```

## Returns

- level
  Number, current battery level in range 0.0 ~ 1.0

## Example

```lua
sys.alert("Battery level: " .. (device.battery_level() * 100) .. "%")
```
Note: Uses function outside this chapter [`sys.alert`](/en/docs/handbook/sys/sys.alert.md)

---

Source: [Copy file or directory (file.copy)](https://xxtouch.app/en/docs/handbook/file/file.copy.md)
Path: handbook/file/file.copy.md

# Copy file or directory (file.copy)


## Declaration

```lua
ok, err = file.copy(src, dst [, mode])
```


## Parameters

- src
    String. Absolute path of the source file or directory.
- dst
    String. Complete absolute path of the resulting file or directory, including the destination file or directory name.
- mode 20250914+
    String, optional. Copy mode. Values:
    - Empty string or omitted: default mode (no-clobber); fail if the destination already exists.
    - "overwrite" or "o": overwrite mode; replace the existing destination (the existing destination will be deleted).
    - "merge" or "m": merge mode (directories only); keep files already in the destination.
    - "overwrite-merge" or "om"/"mo": overwrite-merge mode; merge directories and overwrite files with the same name.

## Returns

- ok
    Boolean. true on success, false on failure.
- err
    String. Error message when the operation fails.


## Description

> Copy the file or directory at `src` as `dst`.
> **This function means “copy as”, not “copy into”.** `dst` specifies the final file or directory; the source file or directory name is not appended automatically. Even if the destination is an existing directory or its path ends in `/`, the source file or directory will not be placed inside it.
> For example, to copy `/a/b/c` into `/d/e/` and keep the name `c`, specify `/d/e/c` as the destination, not just `/d/e/`.
> If the destination already exists, the `mode` parameter determines what happens: the default mode fails, overwrite mode replaces the destination itself, and directory merge modes merge the source directory contents into the destination directory.
> Keywords: copy file, duplicate file, copy directory, duplicate directory, copy folder, duplicate folder.
> **This function is available only in versions released after 20250313.**


## Example

```lua
ok, err = file.copy(XXT_SCRIPTS_PATH..'/1.zip', XXT_SCRIPTS_PATH..'/2.zip')
if not ok then
    sys.alert('Copy failed: '..err)
end
```
**Note**: The code above uses [`sys.alert`](../sys/sys.alert.md), a function outside this chapter.

### Copy to another directory and keep the name

```lua
-- Assume /d/e is an existing directory and /d/e/c does not yet exist
file.copy('/a/b/c', '/d/e/c') -- Correct: copy c as /d/e/c

-- Incorrect: the target is e itself, not c inside e
file.copy('/a/b/c', '/d/e/') -- Default mode fails because the destination already exists

-- Overwrite mode replaces e itself; it does not create /d/e/c (20250914+)
-- file.copy('/a/b/c', '/d/e/', 'overwrite')
```

### Wrap a “copy into directory” function

The following custom wrapper requires a version released after 20250914. The destination directory must already exist. The function keeps the source file or directory name and passes the optional `mode` parameter to `file.copy`. Conflicts with an existing name are still handled according to the specified mode.

```lua
local function file_copy_into(src_path, dst_dir, mode)
    if file.exists(dst_dir) ~= "directory" then
        return false, "Target is not a directory"
    end

    local name, err = file.path.last_component(src_path)
    if not name then
        return false, err
    end
    -- Avoid using the destination directory itself or its parent as the final target.
    if name == "" or name == "/" or name == "." or name == ".." then
        return false, "Source path must end with a file or directory name"
    end

    local dst_path, path_err = file.path.add_component(dst_dir, name)
    if not dst_path then
        return false, path_err
    end
    return file.copy(src_path, dst_path, mode)
end

-- Assume /d/e is an existing directory; copy c as /d/e/c
local ok, err = file_copy_into("/a/b/c", "/d/e/")
if not ok then
    print("Copy failed: "..err)
end

-- To replace /d/e/c, specify overwrite mode when calling the function:
-- file_copy_into("/a/b/c", "/d/e/", "overwrite")
```

**Note**: The code above uses [`file.exists`](file.exists.md), [`file.path.last_component`](file.path.last_component.md), and [`file.path.add_component`](file.path.add_component.md).

---

Source: [Replace color (:replace_color)](https://xxtouch.app/en/docs/handbook/image/imagem_replace_color.md)
Path: handbook/image/imagem_replace_color.md

# Replace color (:replace_color)

## Declaration

```lua
img = img:replace_color(from_color, to_color[, similarity])
```

## Parameters

- from_color
  Integer. Original color
- to_color
  Integer. Color to replace with
- similarity
  Integer, optional. 0~100. Default 100

## Returns

- img
  Image object. Returns the image object itself after replacement

## Description

> Replace a color (or similar colors) on the image with another color
> Mutates the image in-place
> Performance: no data copy during operation

## Example

[`Replace QR background color`](/en/docs/handbook/utils/utils.qr_encode.md)

---

Source: [Create an Execution Task (sys.task)](https://xxtouch.app/en/docs/handbook/sys/sys.task.md)
Path: handbook/sys/sys.task.md

# Create an Execution Task (sys.task)


## Declaration

```lua
task = sys.task(executable_path [, arguments...])
```

## Parameters

- executable_path
    String
- arguments...
    String, optional variadic arguments, defaults to none

## Return Value

- task
    Execution task object, returns an object for controlling or executing the task


## Task Object Methods

|Method|Parameters|Return Value|Description|
|----|----|----|----|
|:launch\(\)|||Launch the task, runs asynchronously|
|:wait_until_exit\(\)|||Synchronously wait for task to finish, blocks all threads until task ends.|
|:set_stdin\(input_stream\)|Pipe \| String||Set the task's input stream. Parameter can be `"std"`, `"/dev/null"`, a file path, or a pipe object. Throws an error if called after task is launched|
|:stdin\(\)||Pipe \| String|Get the task's input stream. May return `"std"`, `"/dev/null"`, a file path, or a pipe object|
|:set_stdout\(output_stream\)|Pipe \| String||Set the task's output stream. Parameter can be `"std"`, `"/dev/null"`, a file path, or a pipe object. Throws an error if called after task is launched|
|:stdout\(\)||Pipe \| String|Get the task's output stream. May return `"std"`, `"/dev/null"`, a file path, or a pipe object|
|:set_stderr\(error_stream\)|Pipe \| String||Set the task's error stream. Parameter can be `"std"`, `"/dev/null"`, a file path, or a pipe object. Throws an error if called after task is launched|
|:stderr\(\)||Pipe \| String|Get the task's error stream. May return `"std"`, `"/dev/null"`, a file path, or a pipe object|
|:set_work_dir\(directory\)|String||Set the task's working directory. Throws an error if called after task is launched|
|:work_dir\(\)||String|Get the task's working directory|
|:set_env\(environment_variables\)|Table||Set the task's environment variable key-value dictionary. Throws an error if called after task is launched|
|:env\(\)||Table|Get the task's environment variable key-value dictionary|
|:pid\(\)||Integer|Get the task's process ID, returns 0 if task has not been launched|
|:is_running\(\)||Boolean|Check if the task is running. Even if `:is_running()` returns false, you should still call `:wait_until_exit()` once on the task to prevent zombie processes|
|:interrupt\(\)||Boolean|Send SIGINT signal to the task's main process|
|:terminate\(\)||Boolean|Send SIGTERM signal to the task's main process|
|:kill\(\)||Boolean|Send SIGKILL signal to all processes of the task, kill operation is automatically executed when the task object is garbage collected|
|:termination_status\(\)||Integer|Get the task's termination status, returns nil, error_message if task has not ended|
|:termination_reason\(\)||String|Get the task's termination reason, returns nil, error_message if task has not ended|


## Pipe Object Methods

|Method|Parameters|Return Value|Description|
|----|----|----|----|
|:read\(\)||String|Read available data from the pipe|
|:write\(data\)|String||Write data to the pipe|
|:wclose\(\)||Boolean, nil \| String|Close the write end of the pipe, returns `true` on success, `false, error_message` on failure|
|:rclose\(\)||Boolean, nil \| String|Close the read end of the pipe, returns `true` on success, `false, error_message` on failure|


## Description

> Creates an execution task and returns an execution task object
> If you don't want to block all threads waiting for the task, you can loop using the task object's `:is_running()` to check if the task is running. Once it's no longer running, you can call `:wait_until_exit()` once to confirm the task has ended
> **Available in versions after 2025-07-05.**


## Example

```lua
-- Simulate the following Shell command
-- echo "Hello World" | /usr/bin/gzip -fc | /usr/bin/gzip -dfc

local comp_tsk = sys.task(jbroot('/usr/bin/gzip'), '-fc')    -- Create compression task
local decomp_tsk = sys.task(jbroot('/usr/bin/gzip'), '-dfc') -- Create decompression task

decomp_tsk:set_stdin(comp_tsk:stdout()) -- Set decompression task's input stream to compression task's output stream

decomp_tsk:launch() -- Launch decompression task
comp_tsk:launch() -- Launch compression task

comp_tsk:stdin():write("Hello World") -- Write data to compression task's input stream
comp_tsk:stdin():wclose() -- Close compression task's input stream write end, indicating input is complete

comp_tsk:wait_until_exit() -- Wait for compression task to finish
decomp_tsk:wait_until_exit() -- Wait for decompression task to finish

nLog(decomp_tsk:stdout():read()) -- Read decompression task's output stream, outputs "Hello World"
```

## Example (Invoke TrollStore Persistence Helper Refresh)

```lua
local persistence_helper_path = app.bundle_path('com.apple.tips')
if not persistence_helper_path then
    nLog('Tips.app not detected, please install the Tips app from AppStore first')
    return
end
local root_helper_path = persistence_helper_path..'/trollstorehelper'
if file.exists(root_helper_path) ~= 'file' then
    nLog('TrollStore Persistence Helper not injected into Tips, please go to TrollStore -> Settings -> Install Persistence Helper and select Tips to inject')
    return
end
local tsk = sys.task(root_helper_path, 'refresh')
tsk:launch()
tsk:wait_until_exit()
sys.killall(9, 'SpringBoard', 'backboardd')
```

## Example (Use TrollStore to Install/Uninstall Apps, Rebuild Icon Cache)

```lua
local function _trollstorehelper(...)
    local troll_path = app.bundle_path('com.opa334.TrollStore')
    assert(type(troll_path) == 'string', 'TrollStore needs to be installed.')
    local tsk = sys.task(troll_path..'/trollstorehelper', ...)
    tsk:set_stdin('/dev/null')
    tsk:launch()
    local outbuf = {}
    local errbuf = {}
    local function drain_stream(stream, buf)
        local data = stream:read('nb')
        if data and #data > 0 then
            buf[#buf + 1] = data
        end
    end
    while tsk:is_running() do
        drain_stream(tsk:stdout(), outbuf)
        drain_stream(tsk:stderr(), errbuf)
        sys.msleep(100)
    end
    tsk:wait_until_exit()
    drain_stream(tsk:stdout(), outbuf)
    drain_stream(tsk:stderr(), errbuf)
    if tsk:termination_status() == 0 then
        local ret = table.concat(outbuf)
        return ret
    else
        local ret = table.concat(errbuf)
        return nil, ret
    end
end

--- Install an App using TrollStore
---@param ipapath string Path to the installation package
---@return string? Installation result text, returns nil on failure
---@return string? Error message, returns nil on success
function troll_install(ipapath)
    return _trollstorehelper('install', ipapath)
end

--- Uninstall an App installed by TrollStore
---@param bid string App bundle identifier
---@return string? Uninstallation result text, returns nil on failure
---@return string? Error message, returns nil on success
function troll_uninstall(bid)
    return _trollstorehelper('uninstall', bid)
end

--- TrollStore rebuild icon cache, may take some time
---@return string? Rebuild result text, returns nil on failure
---@return string? Error message, returns nil on success
function troll_rebuild_icon_cache()
    return _trollstorehelper('refresh-all')
end

-- Example calls
nLog(troll_install(XXT_SCRIPTS_PATH..'/TrollDecrypt.tipa')) -- Install TrollDecrypt
nLog(troll_uninstall('com.fiore.trolldecrypt')) -- Uninstall TrollDecrypt
nLog(troll_rebuild_icon_cache()) -- Rebuild icon cache
```

---

Source: [List files opened by app (app.lsof)](https://xxtouch.app/en/docs/handbook/app/app.lsof.md)
Path: handbook/app/app.lsof.md

# List files opened by app (app.lsof)

## Declaration

```lua
files, err = app.lsof(bid_or_pid)
```

## Parameters

- bid_or_pid
  String (bundle id) or Integer (pid).

## Returns

- files
  Table | nil.
  <details>
  <summary>On success returns a table with the structure below; on failure returns nil.</summary>

  ```lua
  {
      opensockets = {
          {
              fd = integer_value,
              kind = "TCP" | "IN",
              ["local"] = {
                  address = string_value,
                  port = integer_value,
              },
              ["remote"] = {
                  address = string_value,
                  port = integer_value,
              },
          },
          ...
      },
      openfiles = {
          {
              fd = integer_value,
              path = string_value,
          },
          ...
      },
  }
  ```
  </details>

- err
  String | nil. Error message on failure.

## Description

- List file descriptors and socket descriptors opened by the specified app.
- Requires software version 1.3.8 or later.

## Example

```lua
nLog(app.lsof('com.apple.Preferences'))
```

---

Source: [Get current battery state (device.battery_state)](https://xxtouch.app/en/docs/handbook/device/device.battery_state.md)
Path: handbook/device/device.battery_state.md

# Get current battery state (device.battery_state)

## Declaration

```lua
state = device.battery_state()
```

## Returns

- state
  String. One of the following values:
  `"Full"` Connected to power and fully charged
  `"Charging"` Connected to power and charging
  `"Unplugged"` Not connected to power
  `"Unknown"` State is unknown

## Example

```lua
local mapping = {
    Full = "Connected and full",
    Charging = "Connected and charging",
    Unplugged = "Not connected",
    Unknown = "Unknown",
}
sys.alert("Battery state: " .. mapping[device.battery_state()])
```
Note: Uses function outside this chapter [`sys.alert`](/en/docs/handbook/sys/sys.alert.md)

---

Source: [Convert from hex string (string.from_hex)](https://xxtouch.app/en/docs/handbook/ext-string/string.from_hex.md)
Path: handbook/ext-string/string.from_hex.md

# Convert from hex string (string.from_hex)

## Declaration

```lua
data = string.from_hex(hex_text)
```

## Parameters

- hex_text
  string. Hex text to be converted back to string.

## Returns

- data
  string or nil. Returns the converted string. If input is not valid hex, returns nil.

## Description

> The inverse of string.to_hex. Convert printable hex text back to string (or binary data).

## Example

```lua
sys.alert(string.from_hex('e4b880e4ba9be695b0e68dae'))
-- "一些数据"
```
Note: Uses function outside of this chapter: [`sys.alert`](/en/docs/handbook/sys/sys.alert.md)

## More examples

[At the end of this chapter](/en/docs/handbook/ext-string/samples.md)

---

Source: [Find file or directory (file.find)](https://xxtouch.app/en/docs/handbook/file/file.find.md)
Path: handbook/file/file.find.md

# Find file or directory (file.find)

## Declaration

```lua
list = file.find(pattern)
```

## Parameters

- pattern
  Table | String.

## Returns

- list
  Array. The list of matched filenames.

## Description

> Search files or directories using wildcard mode or Lua precise match, and return the matched filenames.
> If `pattern` is a string, wildcard matching is used. Only three wildcards are supported: `*`, `?`, `[ ... ]`.
> If `pattern` is a table, Lua precise matching is used.
> Available in versions after 2025-04-16.

## Example

### Simple wildcard mode

```lua
-- Simple wildcard mode supports only three wildcards: * ? [...]
-- * matches any number of characters (including 0)
-- ? matches exactly one arbitrary character
-- [...] matches one character within the brackets, e.g. [abc]haha.txt matches ahaha.txt, bhaha.txt, chaha.txt
-- [!...] matches one character not in the brackets, e.g. [!abc]haha.txt does not match ahaha.txt/bhaha.txt/chaha.txt, but matches xhaha.txt
local results = file.find("/private/var/mobile/Containers/Shared/AppGroup/*/Library/Preferences/*.plist")
```

### Precise table pattern mode

```lua
-- Precise Lua pattern matching using a table
-- Literal strings are treated as-is; functions that return boolean can be used to validate each segment
local results = file.find{ --<--- note the curly braces
    "/private/var/mobile/Containers/Shared/AppGroup/", -- literal string, no pattern
    function(s) return s:match("^[A-F0-9]+%-[A-F0-9]+%-[A-F0-9]+%-[A-F0-9]+%-[A-F0-9]+$") end, -- function to match this segment
    "/Library/Preferences/",
    function(s) return s:match("%.plist$") end, -- function to match this segment
}
-- You can also wrap a single string by a table to make it a pattern-matching segment
local results = file.find{ --<--- note the curly braces
    "/private/var/mobile/Containers/Shared/AppGroup/", -- literal
    {"^[A-F0-9]+%-[A-F0-9]+%-[A-F0-9]+%-[A-F0-9]+%-[A-F0-9]+$"}, -- pattern string wrapped in a table
    "/Library/Preferences/", -- literal
    {"%.plist$"}, -- pattern string wrapped in a table
}
```

---

Source: [Draw an image onto another (:draw_image)](https://xxtouch.app/en/docs/handbook/image/imagem_draw_image.md)
Path: handbook/image/imagem_draw_image.md

# Draw an image onto another (:draw_image)

## Declaration

```lua
big = big:draw_image(small[, {
   left = left_x,
   top = top_y,
   alpha = alpha,
   background = {
      {color*, tolerance*},
      {color*, tolerance*},
      ...
   },
}])
```

## Parameters

- small
  Image object. The image to draw on big image
- left
  Integer, optional. Left-top x of where to draw the small image on big. Default 0
- top
  Integer, optional. Left-top y. Default 0
- alpha
  Integer, optional. Opacity of small image, 0~255. Default 255
- color*, tolerance*
  Array, optional. Colors on small image whose color difference within tolerance* will be ignored (not drawn). Default: draw all colors

## Returns

- big
  Image object. Returns the big image itself

## Description

> Draw an image onto another image
> Mutates the image in-place
> Performance: no data copy during operation

---

Source: [Query Device Information (sys.mgcopyanswer)](https://xxtouch.app/en/docs/handbook/sys/sys.mgcopyanswer.md)
Path: handbook/sys/sys.mgcopyanswer.md

# Query Device Information (sys.mgcopyanswer)

## Declaration

```lua
answer = sys.mgcopyanswer(question)
```

## Parameters

- question
  String. The question key. Some keys can be found in [MobileGestalt.h](https://github.com/Cykey/ios-reversed-headers/blob/master/MobileGestalt/MobileGestalt.h).

## Returns

- answer
  String | Table | Number | Integer | Boolean | nil. The system's answer. Returns nil if the key is unsupported.

## Description

> Retrieve various system information via [MGCopyAnswer](https://iphonedevwiki.net/index.php/LibMobileGestalt.dylib).
> Examples: get device info, identifiers, carrier info, phone number, etc.

## Examples

```lua
sys.alert("Serial Number: "..sys.mgcopyanswer("SerialNumber"))
sys.alert("IMEI: "..sys.mgcopyanswer("InternationalMobileEquipmentIdentity"))
sys.alert("MEID: "..sys.mgcopyanswer("MobileEquipmentIdentifier"))
sys.alert(string.format('ECID: %016X', sys.mgcopyanswer('UniqueChipID')))

local infos = sys.mgcopyanswer('CarrierBundleInfoArray')
if type(infos) == 'table' and #infos > 0 then
    local info = infos[1]
    if type(info.InternationalMobileSubscriberIdentity) == 'string' then
        sys.alert("Carrier IMSI: "..info.InternationalMobileSubscriberIdentity)
    else
        sys.alert("Cannot read IMSI. Insert a valid SIM card.")
    end
    if type(info.IntegratedCircuitCardIdentity) == 'string' then
        sys.alert("Carrier ICCID: "..info.IntegratedCircuitCardIdentity)
    else
        sys.alert("Cannot read ICCID. Insert a valid SIM card.")
    end
else
    sys.alert("Cannot read carrier info. Insert a valid SIM card.")
end

local phone_number = sys.mgcopyanswer('PhoneNumber')
if sys.mgcopyanswer('SIMTrayStatus') == 'kCTSIMSupportSIMTrayInsertedWithSIM' and type(phone_number) == 'string' then
    sys.alert("Phone Number: "..phone_number)
else
    sys.alert("Cannot read phone number. Insert a valid SIM card.")
end
```

---

Source: [Click a UI Element (ui_element.click)](https://xxtouch.app/en/docs/handbook/ui_element/ui_element.click.md)
Path: handbook/ui_element/ui_element.click.md

# Click a UI Element (ui_element.click)

> **This function is available in versions after 20260507**

## Declaration

```lua
ok, info_or_err = ui_element.click(selector_or_element [, options ])
```

## Parameters

- selector_or_element
  Table. A [selector](selector.md), an element returned by a query, or a coordinate table `{ x = X, y = Y }`.
- options
  Optional, table. See [Common options](options.md).

## Returns

- ok
  Boolean. `true` on success, `nil` on failure.
- info_or_err
  Table on success, string failure reason on failure.

## Description

> Click a button, list item, keyboard key, or another clickable UI element.
> Coordinates in coordinate tables use physical pixels. For fixed-coordinate clicks, prefer [touch.tap](/en/docs/handbook/touch/touch.tap.md).
> If multiple targets match and no unique target can be chosen, this API may return `nil, "ambiguous target"`.

## Example

```lua
local ui_element = require("ui_element")

local ok, info_or_err = ui_element.click({
    title = "Continue",
    role = "button",
})

if not ok then
    sys.toast(info_or_err)
end
```

**Note**: Uses non-chapter API [`sys.toast`](/en/docs/handbook/sys/sys.toast.md).

---

Source: [Install an IPA package (app.install)](https://xxtouch.app/en/docs/handbook/app/app.install.md)
Path: handbook/app/app.install.md

# Install an IPA package (app.install)

## Declaration

```lua
ok = app.install(file_path [, force ])
```

## Parameters

- file_path
  String. Absolute path of the IPA package to install.
- force
  Boolean, optional. Whether to force install. true = overwrite regardless of version (also allows downgrade). false = install only if the IPA version is higher than the currently installed one; skip when the versions are equal or lower. Default: false.

## Returns

- ok
  Boolean. true if installation succeeds; false otherwise.

## Description

- Install an IPA package in the background.
- Stopping the script before installation completes may lead to a half-installed state.
- Ensure AppSync is installed on the target device before calling this function.

## Example

```lua
app.install("/var/mobile/1.ipa", true) -- force overwrite install, useful for downgrading an app
--
if app.install("/var/mobile/1.ipa") then
    -- Installed successfully
else
    -- Install failed
end
```

---

Source: [Turn on Wi‑Fi (device.turn_on_wifi)](https://xxtouch.app/en/docs/handbook/device/device.turn_on_wifi.md)
Path: handbook/device/device.turn_on_wifi.md

# Turn on Wi‑Fi (device.turn_on_wifi)

## Declaration

```lua
device.turn_on_wifi()
```

## Example

```lua
device.turn_on_wifi()
```

---

Source: [Change current working directory (file.chdir)](https://xxtouch.app/en/docs/handbook/file/file.chdir.md)
Path: handbook/file/file.chdir.md

# Change current working directory (file.chdir)

## Declaration

```lua
ok, err = file.chdir(path)
```

## Parameters

- path
  String. Directory path.

## Returns

- ok
  Boolean. true if success, false if failure.
- err
  String. Error message when operation fails.

## Description

> Change current working directory. Equivalent to lfs.chdir.
> Available in versions after 2025-07-05.

## Example

```lua
local success, err = file.chdir("/var/mobile/Media/1ferver/lua/scripts/")
if success then
    sys.alert("Changed successfully")
else
    sys.alert("Change failed: "..err)
end
```
**Note**: Uses [`sys.alert`](/en/docs/handbook/sys/sys.alert.md)

---

Source: [Binarize image object (:binaryzation)](https://xxtouch.app/en/docs/handbook/image/imagem_binaryzation.md)
Path: handbook/image/imagem_binaryzation.md

# Binarize image object (:binaryzation)

## Declaration

```lua
img = img:binaryzation({
    [white_background = white_background,]
    [csim_mode = similarity_mode,]
    [csim_algorithm = color_similarity_algorithm,]
    {color*, tolerance*},
    {color*, tolerance*},
    ...
})
```
```lua
img = img:binaryzation("cx*-cox*,cx*-cox*...")
```

## Parameters

- white_background (since 2025-03-02)
  Boolean, optional. Whether to set the background to white. Default false (white foreground on black background)
- similarity_mode (since 2025-03-02)
  Boolean, optional. Whether to use similarity mode. In similarity mode, tolerance* means similarity instead of color difference. Default false
- color_similarity_algorithm (since 2025-03-02)
  Integer, optional. Only takes effect in similarity mode. Default 0
  <details>
  <summary>Color similarity algorithms</summary>

  ```lua
  0 XXT default algorithm, steep gradient, similarity drops quickly with difference
  1 Manhattan distance, smooth gradient
  2 Euclidean distance, smooth gradient
  ```
  </details>
- color*, tolerance*
  Integer. Whitelist of colors. color* is the color value; tolerance* is the max deviation for that color
- cx*-cox*
  String. Whitelist of colors. cx* is the hex string of color value; cox* is the hex string of max deviation for cx*

## Returns

- img
  Image object. Returns the image object itself after binarization

## Description

> Binarize an image object
> Mutates the image in-place
> Performance: no data copy during operation

## Examples

```lua
local pic = screen.image(462, 242, 569, 272)
pic = pic:binaryzation({
    {0x9D5D39, 0x0F1F26},
    {0xD3D3D2, 0x2C2C2D},
})
```

```lua
local pic = screen.image(462, 242, 569, 272)
pic = pic:binaryzation("9D5D39-0F1F26,D3D3D2-2C2C2D")
```

```lua
local pic = screen.image(462, 242, 569, 272)
pic = pic:binaryzation({
    csim_mode = true,        -- use similarity mode
    csim_algorithm = 2,      -- use Euclidean algorithm
    white_background = true, -- set background to white
    {0x9D5D39, 90},          -- similarity 90% for color 0x9D5D39
    {0xD3D3D2, 90},          -- similarity 90% for color 0xD3D3D2
})
```

---

Source: [Read sysctl Key (sys.ctlbyname)](https://xxtouch.app/en/docs/handbook/sys/sys.ctlbyname.md)
Path: handbook/sys/sys.ctlbyname.md

# Read sysctl Key (sys.ctlbyname)


## Declaration

```lua
data = sys.ctlbyname(key)
```


## Parameters

- key
  String. Full sysctl key name, for example `kern.boottime` or `hw.memsize`.

## Returns

- data
  String. Raw byte data returned by the key. Returns `nil` when the key cannot be read.


## Description

> Calls the underlying sysctlbyname to fetch kernel or hardware runtime parameters.
> Use this to retrieve sysctl values, inspect kernel state, or capture metrics. The raw data often needs additional unpacking.


## Examples

```lua
local raw = sys.ctlbyname('hw.machine')
if type(raw) == 'string' then
    nLog('Device type: '..raw:gsub('%z+$', ''))
else
    nLog('Failed to read hw.machine')
end

local sec, usec = string.unpack('li', sys.ctlbyname('kern.boottime'))
nLog('Seconds since boot', os.time() - sec)
```

---

Source: [Scroll a UI Element or Current Page (ui_element.scroll)](https://xxtouch.app/en/docs/handbook/ui_element/ui_element.scroll.md)
Path: handbook/ui_element/ui_element.scroll.md

# Scroll a UI Element or Current Page (ui_element.scroll)

> **This function is available in versions after 20260507**

## Declaration

```lua
ok, info_or_err = ui_element.scroll(direction [, options ])
ok, info_or_err = ui_element.scroll(selector_or_element, direction [, options ])
```

## Parameters

- selector_or_element
  Optional, table. A [selector](selector.md), an element returned by a query, or a coordinate table `{ x = X, y = Y }`.
- direction
  String. Supported values: `"down"`, `"up"`, `"left"`, `"right"`, `"top"`, `"bottom"`.
- options
  Optional, table. Use `point`, `x`, or `y` to choose the hit point; use `steps` for the step parameter.

## Returns

- ok
  Boolean. `true` on success, `nil` on failure.
- info_or_err
  Table on success, string failure reason on failure.

## Description

> Without a selector, this API tries to scroll the current page.
> With a selector, it tries to scroll the scrollable area that contains the target.
> If you need to scroll several pages, call this API in a Lua loop and check page changes yourself.

## Example

```lua
local ui_element = require("ui_element")

ui_element.scroll("down", {
    point = { x = 200, y = 700 },
})

ui_element.scroll({
    text_contains = "List",
}, "up")
```

---

Source: [Uninstall an app (app.uninstall)](https://xxtouch.app/en/docs/handbook/app/app.uninstall.md)
Path: handbook/app/app.uninstall.md

# Uninstall an app (app.uninstall)

## Declaration

```lua
ok = app.uninstall(bid)
```

## Parameters

- bid
  String. App bundle identifier. You can find it in `XXT App -> More -> App List`.

## Returns

- ok
  Boolean. true if uninstall succeeds; false otherwise.

## Description

- Uninstall an app in the background.
- Stopping the script during uninstallation may lead to a half-uninstalled state.

## Example

```lua
if app.uninstall("com.tencent.mqq") then
    -- Uninstalled successfully
else
    -- Uninstall failed
end
```

---

Source: [Turn off Wi‑Fi (device.turn_off_wifi)](https://xxtouch.app/en/docs/handbook/device/device.turn_off_wifi.md)
Path: handbook/device/device.turn_off_wifi.md

# Turn off Wi‑Fi (device.turn_off_wifi)

## Declaration

```lua
device.turn_off_wifi()
```

## Example

```lua
device.turn_off_wifi()
```

---

Source: [Get current working directory (file.currentdir)](https://xxtouch.app/en/docs/handbook/file/file.currentdir.md)
Path: handbook/file/file.currentdir.md

# Get current working directory (file.currentdir)

## Declaration

```lua
cwd, err = file.currentdir()
```

## Returns

- cwd
  String. Returns the directory path on success; nil on failure.
- err
  String. Error message when operation fails.

## Description

> Get current working directory. Equivalent to lfs.currentdir.
> Available in versions after 2025-07-05.

## Example

```lua
local cwd, err = file.currentdir()
if cwd then
    sys.alert("Current working directory: "..cwd)
else
    sys.alert("Failed to get current working directory: "..err)
end
```
**Note**: Uses [`sys.alert`](/en/docs/handbook/sys/sys.alert.md)

---

Source: [Multi-point color match in image (:is_colors)](https://xxtouch.app/en/docs/handbook/image/imagem_is_colors.md)
Path: handbook/image/imagem_is_colors.md

# Multi-point color match in image (:is_colors)

## Declaration

```lua
is_match = img:is_colors(...)
```

## Returns

- is_match
  Boolean. Whether all points match

## Description

> Multi-point color matching on image
> Parameters and returns are identical to [screen.is_colors](/en/docs/handbook/screen/screen.is_colors.md)

---

Source: [Get System Version (sys.version)](https://xxtouch.app/en/docs/handbook/sys/sys.version.md)
Path: handbook/sys/sys.version.md

# Get System Version (sys.version)

## Declaration

```lua
ver = sys.version()
```

## Returns

- ver
  String. System version.

## Description

> This function can be used in XUI.

## Examples

```lua
sys.alert('Current system version: '..sys.version())
```

---

Source: [Append Text Input (ui_element.input_text)](https://xxtouch.app/en/docs/handbook/ui_element/ui_element.input_text.md)
Path: handbook/ui_element/ui_element.input_text.md

# Append Text Input (ui_element.input_text)

> **This function is available in versions after 20260507**

## Declaration

```lua
ok, info_or_err = ui_element.input_text(selector_or_element, text [, options ])
```

## Parameters

- selector_or_element
  Table. A [selector](selector.md), an element returned by a query, or a coordinate table `{ x = X, y = Y }`.
- text
  String. Text to append.
- options
  Optional, table. See [Common options](options.md).

## Returns

- ok
  Boolean. `true` on success, `nil` on failure.
- info_or_err
  Table on success, string failure reason on failure.

## Description

> This API locates a text input target and appends text.
> To replace existing text, use [`set_text`](ui_element.set_text.md).

## Example

```lua
local ui_element = require("ui_element")

local ok, info_or_err = ui_element.input_text({
    title = "Search",
    role = "text_field",
}, "XXTouch")

if not ok then
    sys.toast(info_or_err)
end
```

**Note**: Uses non-chapter API [`sys.toast`](/en/docs/handbook/sys/sys.toast.md).

---

Source: [Turn on Cellular Data (device.turn_on_data)](https://xxtouch.app/en/docs/handbook/device/device.turn_on_data.md)
Path: handbook/device/device.turn_on_data.md

# Turn on Cellular Data (device.turn_on_data)

## Declaration

```lua
device.turn_on_data()
```

## Example

```lua
device.turn_on_data()
```

---

Source: [Get file attributes (file.attrs)](https://xxtouch.app/en/docs/handbook/file/file.attrs.md)
Path: handbook/file/file.attrs.md

# Get file attributes (file.attrs)

## Declaration

```lua
attrs, err = file.attrs(path [, request])
```

## Parameters

- path
  String.
- request
  Table or String, optional.
  - If a table is provided, the function fills this table with results instead of creating a new one.
  - If a string is provided, returns only the specified field.
  - When not specified, returns a table with all fields.
  - "dev": device where the inode resides
  - "ino": inode number
  - "mode": file type, one of "file", "directory", "link", "socket", "named pipe", "char device", "block device" or "other"
  - "nlink": hard link count
  - "uid": owner user id
  - "gid": owner group id
  - "rdev": device type for special files
  - "access": last access time
  - "modification": last modification time
  - "change": last status change time
  - "size": file size in bytes
  - "permissions": file permissions
  - "blksize": optimal I/O block size
  - "blocks": number of 512-byte blocks allocated

## Returns

- attrs
  Table or nil. Attributes table on success; nil on failure.
- err
  String. Error message when operation fails.

## Description

> Get attributes of a file. If the target is a symbolic link, returns attributes of the file the link points to. Equivalent to `lfs.attributes`.
> Available in versions after 2025-07-05.

## Example

```lua
local info, err = file.attrs("/var/mobile/Media/1ferver/lua/scripts/")
if info then
    sys.alert("File info: "..json.encode(info))
else
    sys.alert("Get attributes failed: "..err)
end
```
**Note**: Uses [`sys.alert`](/en/docs/handbook/sys/sys.alert.md)

---

Source: [Find color in image (:find_color)](https://xxtouch.app/en/docs/handbook/image/imagem_find_color.md)
Path: handbook/image/imagem_find_color.md

# Find color in image (:find_color)

## Declaration

```lua
x, y = img:find_color({
    [find_all = find_all,]
    [max_results = max_results,]
    [max_miss = max_miss,]
    [find_order = find_order,]
    [csim_algorithm = color_similarity_algorithm,]
    {start_x, start_y, start_color[, start_similarity]},
    {dx*, dy*, color*[, similarity*]},
    {dx*, dy*, color*[, similarity*]},
    ...
} [, global_similarity, left, top, right, bottom ])
```

## Parameters

- find_all
  Boolean, optional. If true, returns all matches within range as `{{x1,y1},{x2,y2},...}`. Default false
- max_results
  Integer, optional. When find_all is true, the maximum number of results to return (`<=1000`). Default 100
- max_miss
  Integer, optional. Maximum allowed unmatched points. Default 0 (must match all)
- find_order
  Integer, optional. Search order 1~8. Default 1
  <details>
  <summary>Find order values</summary>

  ```lua
  1 Up-Down-Left-Right
  2 Left-Right-Up-Down
  3 Right-Left-Up-Down
  4 Up-Down-Right-Left
  5 Down-Up-Right-Left
  6 Right-Left-Down-Up
  7 Left-Right-Down-Up
  8 Down-Up-Left-Right
  ```

  Screen API screen.find_color does not have this field
  [Order demo](https://github.com/havonz/XXTouchDebs/blob/master/%E8%84%9A%E6%9C%AC%E6%BA%90%E7%A0%81/%E6%89%BE%E8%89%B2%E6%96%B9%E5%90%91%E6%B5%8B%E8%AF%95.lua)
  </details>
- color_similarity_algorithm (since 2025-03-02)
  Integer, optional. Default 0
  <details>
  <summary>Color similarity algorithms</summary>

  ```lua
  0 XXT default algorithm, steep gradient
  1 Manhattan distance, smooth gradient
  2 Euclidean distance, smooth gradient
  ```
  </details>
- start_x, start_y
  Integer. Starting reference coordinate, used as the anchor for offset calculations. If unsure, use 0, 0
- start_color
  Integer. Color value to search
- start_similarity
  Integer, optional. 1~100. Default 100
- dx*, dy*
  Integer. Offset position relative to the start
- color*
  Integer. Expected color at the offset
- similarity*
  Integer, optional. -100~100. Default 100. Negative similarity means match if similarity is less than abs(value)
- global_similarity
  Integer, optional. Used when a point's similarity is not specified. 1~100. Default 100
- left, top, right, bottom
  Integer, optional. Search region. Default full image

## Returns

- x, y
  Integer. Coordinate of the first matched structure. Returns -1, -1 if not found

## Description

> Use similarity mode to find the first position matching a multi-point color structure within the region
> For offset mode usage, refer to [screen.find_color](/en/docs/handbook/screen/screen.find_color-co.md)

## Example

```lua
img = screen.image()

x, y = img:find_color({
    {  0,   0, 0xec1c23},
    { 12,  -3, 0xffffff, 85},
    {  5, -18, 0x00adee},
    { -1, -10, 0xffc823},
    {  2, -34, 0xa78217},
    { 12, -55, 0xd0d2d2},
}, 90, 0, 0, 100, 100)
--
--[[
    Within the region from 0, 0 at the top left of the image to 100, 100 at the bottom right,
    find the first point whose similarity to 0xec1c23 is greater than 90,
    whose relative coordinate (12, -3) has a color with similarity to 0xffffff greater than 85,
    whose relative coordinate (5, -18) has a color with similarity to 0x00adee greater than 90,
    and for which all remaining points match in the same way.
--]]
--
-- Equivalent code:
--
x, y = img:find_color({
    { 509, 488, 0xec1c23},
    { 521, 485, 0xffffff, 85},
    { 514, 470, 0x00adee},
    { 508, 478, 0xffc823},
    { 511, 454, 0xa78217},
    { 521, 433, 0xd0d2d2},
}, 90, 0, 0, 100, 100)
--
--[[
    Within the region from 0, 0 at the top left of the image to 100, 100 at the bottom right,
    find the first point whose similarity to 0xec1c23 is greater than 90,
    whose relative coordinate (521-509, 485-488) has a color with similarity to 0xffffff greater than 85,
    whose relative coordinate (514-509, 470-488) has a color with similarity to 0x00adee greater than 90,
    and for which all remaining points match in the same way.
--]]
```

---

Source: [Get CoreFoundation Version (sys.cfversion)](https://xxtouch.app/en/docs/handbook/sys/sys.cfversion.md)
Path: handbook/sys/sys.cfversion.md

# Get CoreFoundation Version (sys.cfversion)

## Declaration

```lua
ver = sys.cfversion()
```

## Returns

- ver
  Number. CoreFoundation version of the device. CF version can be used to infer iOS version range. See [CoreFoundationVersionNumber](https://github.com/theos/headers/blob/master/version.h).

## Description

> Available in app version 1.3.8 or later.

## Examples

```lua
sys.alert('Current CoreFoundation version: '..sys.cfversion())
```

---

Source: [Set Text Content (ui_element.set_text)](https://xxtouch.app/en/docs/handbook/ui_element/ui_element.set_text.md)
Path: handbook/ui_element/ui_element.set_text.md

# Set Text Content (ui_element.set_text)

> **This function is available in versions after 20260507**

## Declaration

```lua
ok, info_or_err = ui_element.set_text(selector_or_element, text [, options ])
```

## Parameters

- selector_or_element
  Table. A [selector](selector.md), an element returned by a query, or a coordinate table `{ x = X, y = Y }`.
- text
  String. Text to set.
- options
  Optional, table. See [Common options](options.md).

## Returns

- ok
  Boolean. `true` on success, `nil` on failure.
- info_or_err
  Table on success, string failure reason on failure.

## Description

> Set the content of a text input target to the given text.
> If the target control does not allow direct text setting, this API may fail.

## Example

```lua
local ui_element = require("ui_element")

ui_element.set_text({
    title = "Search",
    role = "text_field",
}, "XXTouch")
```

---

Source: [Turn off Cellular Data (device.turn_off_data)](https://xxtouch.app/en/docs/handbook/device/device.turn_off_data.md)
Path: handbook/device/device.turn_off_data.md

# Turn off Cellular Data (device.turn_off_data)

## Declaration

```lua
device.turn_off_data()
```

## Example

```lua
device.turn_off_data()
```

---

Source: [Get symlink attributes (file.lattrs)](https://xxtouch.app/en/docs/handbook/file/file.lattrs.md)
Path: handbook/file/file.lattrs.md

# Get symlink attributes (file.lattrs)

## Declaration

```lua
attrs, err = file.lattrs(path [, request])
```

## Parameters

- path
  String.
- request
  Table or String, optional.
  - If a table is provided, the function fills this table with results instead of creating a new one.
  - If a string is provided, returns only the specified field.
  - When not specified, returns a table with all fields.
  - "dev": device where the inode resides
  - "ino": inode number
  - "mode": file type, one of "file", "directory", "link", "socket", "named pipe", "char device", "block device" or "other"
  - "nlink": hard link count
  - "uid": owner user id
  - "gid": owner group id
  - "rdev": device type for special files
  - "access": last access time
  - "modification": last modification time
  - "change": last status change time
  - "size": file size in bytes
  - "permissions": file permissions
  - "blksize": optimal I/O block size
  - "blocks": number of 512-byte blocks allocated
  - "target": symlink target path

## Returns

- attrs
  Table or nil. Attributes table on success; nil on failure.
- err
  String. Error message when operation fails.

## Description

> Get file attributes. If the target is a symbolic link, returns information about the link itself (not the file it points to). Equivalent to `lfs.symlinkattributes`.
> Available in versions after 2025-07-05.

## Example

```lua
local info, err = file.lattrs("/var/mobile/Media/1ferver/lua/scripts/")
if info then
    sys.alert("File info: "..json.encode(info))
else
    sys.alert("Get attributes failed: "..err)
end
```
**Note**: Uses [`sys.alert`](/en/docs/handbook/sys/sys.alert.md)

---

Source: [Find Image in Image (:find_image)](https://xxtouch.app/en/docs/handbook/image/imagem_find_image.md)
Path: handbook/image/imagem_find_image.md

# Find Image in Image (:find_image)

## Declaration

```lua
x, y = bigImage:find_image(smallImage [, confidence, left, top, right, bottom ])
result = bigImage:find_image(smallImage [, options, left, top, right, bottom ])
```

## Parameters

- smallImage
  Image object. The template image to search for.

## Returns

- x, y
  Integers. Top-left coordinates of the best match position in the big image.

## Description

> Search for a small image inside a big image. Parameters and return values are the same as [`screen.find_image`](/en/docs/handbook/screen/screen.find_image.md).
> **Available in version 1.3.8 and later.**

---

Source: [Get XXTouch Version (sys.xtversion)](https://xxtouch.app/en/docs/handbook/sys/sys.xtversion.md)
Path: handbook/sys/sys.xtversion.md

# Get XXTouch Version (sys.xtversion)

## Declaration

```lua
ver = sys.xtversion()
```

## Returns

- ver
  String. XXTouch version.

## Description

> This function can be used in XUI.

## Examples

```lua
sys.alert('Current XXTouch version: '..sys.xtversion())
```

---

Source: [Clear Text Content (ui_element.clear_text)](https://xxtouch.app/en/docs/handbook/ui_element/ui_element.clear_text.md)
Path: handbook/ui_element/ui_element.clear_text.md

# Clear Text Content (ui_element.clear_text)

> **This function is available in versions after 20260507**

## Declaration

```lua
ok, info_or_err = ui_element.clear_text(selector_or_element [, options ])
```

## Parameters

- selector_or_element
  Table. A [selector](selector.md), an element returned by a query, or a coordinate table `{ x = X, y = Y }`.
- options
  Optional, table. See [Common options](options.md).

## Returns

- ok
  Boolean. `true` on success, `nil` on failure.
- info_or_err
  Table on success, string failure reason on failure.

## Description

> Clear a text input target.
> Whether a particular control accepts clearing depends on the current app screen.

## Example

```lua
local ui_element = require("ui_element")

ui_element.clear_text({
    title = "Search",
    role = "text_field",
})
```

---

Source: [Turn on Bluetooth (device.turn_on_bluetooth)](https://xxtouch.app/en/docs/handbook/device/device.turn_on_bluetooth.md)
Path: handbook/device/device.turn_on_bluetooth.md

# Turn on Bluetooth (device.turn_on_bluetooth)

## Declaration

```lua
device.turn_on_bluetooth()
```

## Example

```lua
device.turn_on_bluetooth()
```

---

Source: [Create a file link (file.link)](https://xxtouch.app/en/docs/handbook/file/file.link.md)
Path: handbook/file/file.link.md

# Create a file link (file.link)

## Declaration

```lua
ok, err = file.link(src, dst [, symlink])
```

## Parameters

- src
  String. Source file path.
- dst
  String. Destination file path.
- symlink
  Boolean, optional. If true, create a symbolic link; otherwise create a hard link.

## Returns

- ok
  Boolean. true if success, false if failure.
- err
  String. Error message when operation fails.

## Description

> Create a file link. Equivalent to lfs.link.
> Available in versions after 2025-07-05.

## Example

```lua
local info, err = file.link(jbroot("/var/mobile/Media/1ferver"), "/var/mobile/Media/1ferver", true)
if info then
    sys.alert("Symlink created successfully")
else
    sys.alert("Create symlink failed: "..err)
end
```
**Note**: Uses [`sys.alert`](/en/docs/handbook/sys/sys.alert.md)

---

Source: [! OCR text from image (:ocr_text)](https://xxtouch.app/en/docs/handbook/image/imagem_ocr_text.md)
Path: handbook/image/imagem_ocr_text.md

# ! OCR text from image (:ocr_text)

## Declaration

```lua
text, details = img:ocr_text([ engine_options, binarization ])
```

## Parameters

- engine_options
  Optional, table. Choose language and OCR engine
  <details>
  <summary>Structure</summary>

  ```lua
  {
      -- engine = "apple" uses Vision.framework (iOS 13+)
      -- Use image.vision_supported_recognition_languages() to list supported models
      -- engine = "paddle" uses Paddle-Lite. Use lang like "ppocr_ch" for model path /var/mobile/Media/1ferver/models/ppocr_ch
      -- Paddle-Lite supports Slim *.nb models
      engine = "apple" | "paddle" | "tesseract",
      lang = "zh-Hans",
  }
  ```
  </details>

  <details>
  <summary>Vision.framework supported OCR models by iOS version</summary>

  ```lua
  { -- iOS 13
      [1] = "en-US",
  }

  { -- iOS 14~15
      [1] = "en-US",
      [2] = "fr-FR",
      [3] = "it-IT",
      [4] = "de-DE",
      [5] = "es-ES",
      [6] = "pt-BR",
      [7] = "zh-Hans",
      [8] = "zh-Hant",
  }

  { -- iOS 16
      [ 1] = "en-US",
      [ 2] = "fr-FR",
      [ 3] = "it-IT",
      [ 4] = "de-DE",
      [ 5] = "es-ES",
      [ 6] = "pt-BR",
      [ 7] = "zh-Hans",
      [ 8] = "zh-Hant",
      [ 9] = "yue-Hans",
      [10] = "yue-Hant",
      [11] = "ko-KR",
      [12] = "ja-JP",
      [13] = "ru-RU",
      [14] = "uk-UA",
  }
  ```
  </details>

- binarization
  Number: threshold. See [Auto binarization](/en/docs/handbook/image/imagem_cv_binaryzation.md)
  Table: custom binarization with tolerances. See [Manual binarization](/en/docs/handbook/image/imagem_binaryzation.md)
  String: custom binarization with tolerances. See [Manual binarization](/en/docs/handbook/image/imagem_binaryzation.md)

## Returns

- text
  String. Recognized text
- details
  Table
  <details>
  <summary>Details structure</summary>

  ```lua
  {
      {
          ["y"] = number_value,
          ["x"] = number_value,
          ["w"] = number_value,
          ["h"] = number_value,
          ["confidence"] = number_value(0.0000 ~ 1.0000),
          ["text"] = string_value,
      },
      ...
  }
  ```
  </details>

## Description

> Recognize text in an image. Usage is the same as [screen.ocr_text](/en/docs/handbook/screen/screen.ocr_text.md), except that no region parameters are needed.
> Available in app version >= 1.3.8
> [PaddleLite Simplified Chinese standard model (requires extraction)](https://xxtouch.lanzout.com/iL57a38ww71e)
> [PaddleLite Simplified Chinese full model (requires extraction)](https://xxtouch.lanzout.com/iiQYx38ww6fc)
> [PaddleLite Traditional Chinese model (requires extraction)](https://xxtouch.lanzout.com/iNNpU38wyb3c)
> [PaddleLite Japanese model (requires extraction)](https://xxtouch.lanzout.com/iYXfK3boux0h)
> [PaddleLite Korean model (requires extraction)](https://xxtouch.lanzout.com/ieCCH3bouxda)
> [PaddleLite English alphanumeric model (requires extraction)](https://xxtouch.lanzout.com/iiKtE3994q8f)
> You can also download models from the [PaddleOCR model list](https://github.com/PaddlePaddle/PaddleOCR/blob/main/docs/version2.x/ppocr/model_list.md), convert them to `det_opt.nb`, `cls_opt.nb`, and `rec_opt.nb`, and pair them with the appropriate [`dict.txt`](https://github.com/PaddlePaddle/PaddleOCR/tree/main/ppocr/utils/dict)

## Examples

```lua
-- >=1.3.8
local img = image.load_file(XXT_SCRIPTS_PATH..'/1.png')

txt, info = img:ocr_text("en-US")
sys.toast("Result: "..txt:atrim())

txt, info = img:ocr_text("zh-Hans")
sys.toast("Result: "..txt:atrim())

txt, info = img:ocr_text({ engine = "apple", lang = "zh-Hans" }, "9D5D39-0F1F26,D3D3D2-2C2C2D")
sys.toast("Result: "..txt:atrim())

txt, info = img:ocr_text({ engine = "paddle", lang = "ppocr_ch" })
sys.toast("Result: "..txt:atrim())
```
Note: Uses functions outside this chapter [`sys.toast`](/en/docs/handbook/sys/sys.toast.md), [`string.atrim`](/en/docs/handbook/ext-string/string.atrim.md)

## Legacy examples (not recommended)

```lua
local img = image.load_file(XXT_SCRIPTS_PATH..'/1.png')
local txt = img:ocr_text()
sys.toast("Result: "..txt:atrim())

local txt = img:ocr_text("eng", "9D5D39-0F1F26,D3D3D2-2C2C2D")
sys.toast("Result: "..txt:atrim())

local txt = img:ocr_text("eng", { {0x9D5D39, 0x0F1F26}, {0xD3D3D2, 0x2C2C2D} })
sys.toast("Result: "..txt:atrim())

local txt = img:ocr_text({ lang = "chi_sim", white_list = "你我他" })
sys.toast("Result: "..txt:atrim())

local txt = img:ocr_text({ lang = "eng", white_list = "1234567890" }, "9D5D39-0F1F26,D3D3D2-2C2C2D")
sys.toast("Result: "..txt:atrim())
```
Note: Uses functions outside this chapter [`sys.toast`](/en/docs/handbook/sys/sys.toast.md), [`string.atrim`](/en/docs/handbook/ext-string/string.atrim.md)

---

Source: [Allow Apps to Request to Track (sys.user_tracking / sys.set_user_tracking)](https://xxtouch.app/en/docs/handbook/sys/sys.user_tracking.md)
Path: handbook/sys/sys.user_tracking.md

# Allow Apps to Request to Track (sys.user_tracking / sys.set_user_tracking)

> **This function is available in versions after 20260529**

## Declaration

```lua
allow_tracking_requests = sys.user_tracking()
success = sys.set_user_tracking(allow_tracking_requests)
```

## Parameters

- allow_tracking_requests
  Boolean. Whether apps are allowed to request tracking. `true` means allowed, `false` means not allowed.

## Returns

- allow_tracking_requests
  Boolean or nil. Whether apps are currently allowed to request tracking. Returns `nil` when the value cannot be read.
- success
  Boolean. Whether the setting was applied successfully.

## Description

> Gets or sets the `Settings > Privacy & Security > Tracking > Allow Apps to Request to Track` switch.
> The setting name or location may differ slightly across iOS versions.

## Example

```lua
local allow = sys.user_tracking()

if type(allow) == "boolean" then
    sys.set_user_tracking(false)

    -- Restore the previous state when needed
    sys.set_user_tracking(allow)
else
    sys.toast("Cannot read tracking setting")
end
```

---

Source: [Toggle Control State (ui_element.toggle)](https://xxtouch.app/en/docs/handbook/ui_element/ui_element.toggle.md)
Path: handbook/ui_element/ui_element.toggle.md

# Toggle Control State (ui_element.toggle)

> **This function is available in versions after 20260507**

## Declaration

```lua
ok, info_or_err = ui_element.toggle(selector_or_element [, options ])
```

## Parameters

- selector_or_element
  Table. A [selector](selector.md), an element returned by a query, or a coordinate table `{ x = X, y = Y }`.
- options
  Optional, table. See [Common options](options.md).

## Returns

- ok
  Boolean. `true` on success, `nil` on failure.
- info_or_err
  Table on success, string failure reason on failure.

## Description

> Toggle a switch, checkbox, or another control whose confirmed state can be read.
> If the target state cannot be read, this API may return `nil, "state unavailable"`.

## Example

```lua
local ui_element = require("ui_element")

ui_element.toggle({
    title = "Airplane Mode",
    role = "switch",
})
```

---

Source: [Turn off Bluetooth (device.turn_off_bluetooth)](https://xxtouch.app/en/docs/handbook/device/device.turn_off_bluetooth.md)
Path: handbook/device/device.turn_off_bluetooth.md

# Turn off Bluetooth (device.turn_off_bluetooth)

## Declaration

```lua
device.turn_off_bluetooth()
```

## Example

```lua
device.turn_off_bluetooth()
```

---

Source: [Recursively create directories (file.mkdir_p)](https://xxtouch.app/en/docs/handbook/file/file.mkdir_p.md)
Path: handbook/file/file.mkdir_p.md

# Recursively create directories (file.mkdir_p)

## Declaration

```lua
ok, err = file.mkdir_p(path [, uid , gid , mode])
```

## Parameters

- path
  String.
- uid
  Integer, optional. Default 501.
- gid
  Integer, optional. Default 501.
- mode
  Integer | String, optional. Default "0777".

## Returns

- ok
  Boolean. true if success, false if failure.
- err
  String. Error message when operation fails.

## Description

> Recursively create directories. When no parameters are supplied, the created directories default to owner UID/GID 501 and permission octal `0777`.
> Keywords: create folder, make directory.
> **This function is available only in versions released after 2025-07-05.**

## Example

```lua
local success, err = file.mkdir_p("/var/mobile/Media/1ferver/lua/scripts/a/b/c/d")
if success then
    sys.alert("Created successfully")
else
    sys.alert("Create failed: "..err)
end
```
**Note**: Uses [`sys.alert`](/en/docs/handbook/sys/sys.alert.md)

---

Source: [Decode a QR code image (:qr_decode)](https://xxtouch.app/en/docs/handbook/image/imagem_qr_decode.md)
Path: handbook/image/imagem_qr_decode.md

# Decode a QR code image (:qr_decode)

## Declaration

```lua
text = img:qr_decode()
```

## Returns

- text
  String or nil. Decoded text if the image contains a QR code; otherwise nil

## Description

> Decode an image that contains a QR code. It may still work even if there is background clutter

## Examples

```lua
-- Decode a local QR image file
local img = image.load_file("/var/mobile/qr.png")
if img then
    local str = img:qr_decode()
    img:destroy()
    if str then
        sys.alert("Success\n"..str)
    else
        sys.alert("Failed")
    end
else
    sys.alert("Load failed: file may not exist")
end
```
```lua
-- Decode QR code shown on current screen
local str = screen.image():qr_decode()
if str then
    sys.alert("Success\n"..str)
else
    sys.alert("Failed")
end
```
Note: Uses function outside this chapter [`sys.alert`](/en/docs/handbook/sys/sys.alert.md)

---

Source: [Personalized Ads (sys.personalized_advertising / sys.set_personalized_advertising)](https://xxtouch.app/en/docs/handbook/sys/sys.personalized_advertising.md)
Path: handbook/sys/sys.personalized_advertising.md

# Personalized Ads (sys.personalized_advertising / sys.set_personalized_advertising)

> **This function is available in versions after 20260529**

## Declaration

```lua
allow_personalized_ads = sys.personalized_advertising()
success = sys.set_personalized_advertising(allow_personalized_ads)
```

## Parameters

- allow_personalized_ads
  Boolean. Whether personalized ads are allowed. `true` means allowed, `false` means not allowed.

## Returns

- allow_personalized_ads
  Boolean or nil. Whether personalized ads are currently allowed. Returns `nil` when the value cannot be read.
- success
  Boolean. Whether the setting was applied successfully.

## Description

> Gets or sets the `Settings > Privacy & Security > Apple Advertising > Personalized Ads` switch.
> The setting name or location may differ slightly across iOS versions.

## Example

```lua
local allow = sys.personalized_advertising()

if type(allow) == "boolean" then
    sys.set_personalized_advertising(false)

    -- Restore the previous state when needed
    sys.set_personalized_advertising(allow)
else
    sys.toast("Cannot read personalized ads setting")
end
```

---

Source: [Set Checked State (ui_element.set_checked)](https://xxtouch.app/en/docs/handbook/ui_element/ui_element.set_checked.md)
Path: handbook/ui_element/ui_element.set_checked.md

# Set Checked State (ui_element.set_checked)

> **This function is available in versions after 20260507**

## Declaration

```lua
ok, info_or_err = ui_element.set_checked(selector_or_element, checked [, options ])
```

## Parameters

- selector_or_element
  Table. A [selector](selector.md), an element returned by a query, or a coordinate table `{ x = X, y = Y }`.
- checked
  Boolean. `true` means on or selected; `false` means off or unselected.
- options
  Optional, table. See [Common options](options.md).

## Returns

- ok
  Boolean. `true` on success, `nil` on failure.
- info_or_err
  Table on success, string failure reason on failure.

## Description

> If the target is already in the requested state, this API returns success.
> The target control must expose a reliable confirmed state.

## Example

```lua
local ui_element = require("ui_element")

ui_element.set_checked({
    title = "Airplane Mode",
    role = "switch",
}, false)
```

---

Source: [Turn on Airplane Mode (device.turn_on_airplane)](https://xxtouch.app/en/docs/handbook/device/device.turn_on_airplane.md)
Path: handbook/device/device.turn_on_airplane.md

# Turn on Airplane Mode (device.turn_on_airplane)

## Declaration

```lua
device.turn_on_airplane()
```

## Description

> Turn on Airplane Mode (disables all wireless network connections)

## Example

```lua
device.turn_on_airplane()
```

---

Source: [Update access and modification time (file.touch)](https://xxtouch.app/en/docs/handbook/file/file.touch.md)
Path: handbook/file/file.touch.md

# Update access and modification time (file.touch)

## Declaration

```lua
ok, err = file.touch(path [, atime , mtime])
```

## Parameters

- path
  String.
- atime
  Integer, optional. Seconds timestamp. If not specified, uses `os.time()`.
- mtime
  Integer, optional. Seconds timestamp. If not specified, uses `atime`.

## Returns

- ok
  Boolean. true if success, false if failure.
- err
  String. Error message when operation fails.

## Description

> Update access and modification time. Equivalent to lfs.touch.
> Available in versions after 2025-07-05.

## Example

```lua
local success, err = file.touch("/var/mobile/Media/1ferver/lua/scripts/", os.time() - 86400 * 3, os.time() - 86400 * 2)
if success then
    sys.alert("Updated successfully")
else
    sys.alert("Update failed: "..err)
end
```
**Note**: Uses [`sys.alert`](/en/docs/handbook/sys/sys.alert.md)

---

Source: [Destroy an image object (:destroy)](https://xxtouch.app/en/docs/handbook/image/imagem_destroy.md)
Path: handbook/image/imagem_destroy.md

# Destroy an image object (:destroy)

## Declaration

```lua
img:destroy()
```

## Description

> Immediately release memory of the image object. The destroyed image cannot be used again
> Performance tip: if you frequently create new images, call this to avoid high memory usage that may freeze/crash the device
> If not creating images frequently, you may omit; no memory leak. Lua GC will reclaim later

## Example

```lua
sys.alert("Click OK, start monitoring screen in 1s")
sys.msleep(1000)
local img = screen.image()
while 1 do
    local scn = screen.image()
    local x, y, s = scn:cv_find_image(img)
    scn:destroy()
    if s < 95 then break end
    sys.msleep(10)
end
sys.alert("Screen changed")
```
Note: This example uses functions outside this chapter [`sys.alert`](/en/docs/handbook/sys/sys.alert.md), [`sys.msleep`](/en/docs/handbook/sys/sys.msleep.md)

---

Source: [Location Services (sys.location_services / sys.set_location_services)](https://xxtouch.app/en/docs/handbook/sys/sys.location_services.md)
Path: handbook/sys/sys.location_services.md

# Location Services (sys.location_services / sys.set_location_services)

> **This function is available in versions after 20260529**

## Declaration

```lua
location_services_enabled = sys.location_services()
success = sys.set_location_services(location_services_enabled)
```

## Parameters

- location_services_enabled
  Boolean. Whether Location Services are enabled. `true` means enabled, `false` means disabled.

## Returns

- location_services_enabled
  Boolean or nil. Whether Location Services are currently enabled. Returns `nil` when the value cannot be read.
- success
  Boolean. Whether the setting was applied successfully.

## Description

> Gets or sets the main `Settings > Privacy & Security > Location Services` switch.
> The setting name or location may differ slightly across iOS versions.

## Example

```lua
local enabled = sys.location_services()

if type(enabled) == "boolean" then
    sys.set_location_services(false)

    -- Restore the previous state when needed
    sys.set_location_services(enabled)
else
    sys.toast("Cannot read Location Services setting")
end
```

---

Source: [Set Control Value (ui_element.set_value)](https://xxtouch.app/en/docs/handbook/ui_element/ui_element.set_value.md)
Path: handbook/ui_element/ui_element.set_value.md

# Set Control Value (ui_element.set_value)

> **This function is available in versions after 20260507**

## Declaration

```lua
ok, info_or_err = ui_element.set_value(selector_or_element, value [, options ])
```

## Parameters

- selector_or_element
  Table. A [selector](selector.md), an element returned by a query, or a coordinate table `{ x = X, y = Y }`.
- value
  String, integer, number, or boolean. Control value to set.
- options
  Optional, table. See [Common options](options.md).

## Returns

- ok
  Boolean. `true` on success, `nil` on failure.
- info_or_err
  Table on success, string failure reason on failure.

## Description

> Use this API for controls that support direct value setting.
> For sliders, you may try a number from `0.0` to `1.0`, or a percentage string such as `"50%"`.
> If the target control does not actually change, this API may return `nil, "value unchanged"`.

## Example

```lua
local ui_element = require("ui_element")

ui_element.set_value({
    role = "slider",
    index = 1,
}, 0.5)
```

---

Source: [Turn off Airplane Mode (device.turn_off_airplane)](https://xxtouch.app/en/docs/handbook/device/device.turn_off_airplane.md)
Path: handbook/device/device.turn_off_airplane.md

# Turn off Airplane Mode (device.turn_off_airplane)

## Declaration

```lua
device.turn_off_airplane()
```

## Description

> Turn off Airplane Mode (restores wireless network connections)

## Example

```lua
device.turn_off_airplane()
```

---

Source: [Create a ZIP archive (file.zip)](https://xxtouch.app/en/docs/handbook/file/file.zip.md)
Path: handbook/file/file.zip.md

# Create a ZIP archive (file.zip)

## Declaration

```lua
ok, err = file.zip(zipPath, filesOrDir [, password])
```

## Parameters

- zipPath
  String. Output path of the ZIP file to create.
- filesOrDir
  Table | String.
  - Table: each element is `{ sourcePath, archivePath }`, where `archivePath` is the relative path inside the ZIP.
  - String: a directory path to pack into the ZIP.
- password
  String. Optional. If provided, creates an encrypted ZIP.

## Returns

- ok
  Boolean. true if success, false if failure.
- err
  String. Error message when operation fails.

## Description

> Compress files or a directory into a ZIP archive.
> When `filesOrDir` is a table, you can precisely control the relative paths written into the ZIP. When it is a string, the entire directory content is packed.
> Available in versions after 2025-09-14.

## Examples

### Use a table to set archive paths

```lua
local ok, err = file.zip(XXT_SCRIPTS_PATH.."/out.zip", {
    { XXT_SCRIPTS_PATH.."/data/readme.txt",  "docs/readme.txt" },
    { XXT_SCRIPTS_PATH.."/assets/logo.png",  "assets/images/logo.png" },
}, "123456")
if not ok then
    sys.alert("Zip failed: "..err)
else
    sys.alert("Zip succeeded: "..XXT_SCRIPTS_PATH.."/out.zip")
end
```

### Zip a directory directly

```lua
local ok, err = file.zip(XXT_SCRIPTS_PATH.."/project.zip", XXT_SCRIPTS_PATH.."/project")
if not ok then
    sys.alert("Zip failed: "..err)
else
    sys.alert("Zip succeeded: "..XXT_SCRIPTS_PATH.."/project.zip")
end
```
**Note**: Uses [`sys.alert`](/en/docs/handbook/sys/sys.alert.md)

---

Source: [cv - Find image within image (:cv_find_image)](https://xxtouch.app/en/docs/handbook/image/imagem_cv_find_image.md)
Path: handbook/image/imagem_cv_find_image.md

# cv - Find image within image (:cv_find_image)

## Declaration

```lua
x, y, score = big:cv_find_image(small)
```

## Parameters

- small
  Image object. The small image to search for

## Returns

- x, y
  Integer. Top-left coordinates of the best match location in the big image
- score
  Number. Similarity at the best match location, in 0~100

## Description

> OpenCV extension: find the position of one image inside another image object

---

Source: [Increase Control Value (ui_element.increase)](https://xxtouch.app/en/docs/handbook/ui_element/ui_element.increase.md)
Path: handbook/ui_element/ui_element.increase.md

# Increase Control Value (ui_element.increase)

> **This function is available in versions after 20260507**

## Declaration

```lua
ok, info_or_err = ui_element.increase(selector_or_element [, options ])
```

## Parameters

- selector_or_element
  Table. A [selector](selector.md), an element returned by a query, or a coordinate table `{ x = X, y = Y }`.
- options
  Optional, table. Use `steps` to provide a step parameter.

## Returns

- ok
  Boolean. `true` on success, `nil` on failure.
- info_or_err
  Table on success, string failure reason on failure.

## Description

> Use this API for sliders, pickers, and other controls that support adjustment.
> The target control decides how much each call increases. For precise control, call it in a Lua loop and read the result.

## Example

```lua
local ui_element = require("ui_element")

ui_element.increase({
    role = "slider",
    index = 1,
})
```

---

Source: [Connect to selected VPN (device.turn_on_vpn)](https://xxtouch.app/en/docs/handbook/device/device.turn_on_vpn.md)
Path: handbook/device/device.turn_on_vpn.md

# Connect to selected VPN (device.turn_on_vpn)

## Declaration

```lua
device.turn_on_vpn()
```

## Description

> Try to connect to the currently selected VPN; if no VPN is selected, this call is a no-op.
> **Note:** This function is not very stable. Prefer the more stable [VPN config module (vpnconf)](/en/docs/handbook/vpnconf/index.md).

## Example

```lua
device.turn_on_vpn()
```

---

Source: [Unzip a ZIP file (file.unzip)](https://xxtouch.app/en/docs/handbook/file/file.unzip.md)
Path: handbook/file/file.unzip.md

# Unzip a ZIP file (file.unzip)

## Declaration

```lua
ok, err = file.unzip(zipPath, destDir [, password])
```

## Parameters

- zipPath
  String. Absolute path of the ZIP file to extract.
- destDir
  String. Destination directory to extract into.
- password
  String. Optional. Provide if the ZIP is password-protected.

## Returns

- ok
  Boolean. true if success, false if failure.
- err
  String. Error message when operation fails.

## Description

> Extract a ZIP file to a target directory.
> Extracted files are set to permission 0755. Owner UID is 501 and group GID is 501.
> Available in versions after 2025-09-14.

## Examples

```lua
local ok, err = file.unzip(XXT_SCRIPTS_PATH.."/archive.zip", XXT_SCRIPTS_PATH.."/unzipped", "123456")
if not ok then
    sys.alert("Unzip failed: "..err)
else
    sys.alert("Unzip succeeded: "..XXT_SCRIPTS_PATH.."/unzipped")
end
```

```lua
-- Without password
local ok, err = file.unzip(XXT_SCRIPTS_PATH.."/project.zip", XXT_SCRIPTS_PATH.."/project")
if not ok then
    sys.alert("Unzip failed: "..err)
end
```
**Note**: Uses [`sys.alert`](/en/docs/handbook/sys/sys.alert.md)

---

Source: [cv - Auto binarize image (:cv_binaryzation)](https://xxtouch.app/en/docs/handbook/image/imagem_cv_binaryzation.md)
Path: handbook/image/imagem_cv_binaryzation.md

# cv - Auto binarize image (:cv_binaryzation)

## Declaration

```lua
img = img:cv_binaryzation([ threshold ])
```

## Parameters

- threshold
  Number, optional. Threshold in range 0~255. Default uses theoretically best threshold

## Returns

- img
  Image object. Returns the image object itself after binarization

## Description

> OpenCV extension: automatically binarize an image
> Mutates the image in-place
> Performance: no data copy during operation

---

Source: [Decrease Control Value (ui_element.decrease)](https://xxtouch.app/en/docs/handbook/ui_element/ui_element.decrease.md)
Path: handbook/ui_element/ui_element.decrease.md

# Decrease Control Value (ui_element.decrease)

> **This function is available in versions after 20260507**

## Declaration

```lua
ok, info_or_err = ui_element.decrease(selector_or_element [, options ])
```

## Parameters

- selector_or_element
  Table. A [selector](selector.md), an element returned by a query, or a coordinate table `{ x = X, y = Y }`.
- options
  Optional, table. Use `steps` to provide a step parameter.

## Returns

- ok
  Boolean. `true` on success, `nil` on failure.
- info_or_err
  Table on success, string failure reason on failure.

## Description

> Use this API for sliders, pickers, and other controls that support adjustment.
> The target control decides how much each call decreases. For precise control, call it in a Lua loop and read the result.

## Example

```lua
local ui_element = require("ui_element")

ui_element.decrease({
    role = "picker",
    index = 1,
}, {
    steps = 2,
})
```

---

Source: [Disconnect current VPN (device.turn_off_vpn)](https://xxtouch.app/en/docs/handbook/device/device.turn_off_vpn.md)
Path: handbook/device/device.turn_off_vpn.md

# Disconnect current VPN (device.turn_off_vpn)

## Declaration

```lua
device.turn_off_vpn()
```

## Description

> Disconnect the currently connected VPN; if no VPN is connecting or connected, this call is a no-op.
> **Note:** This function is not very stable and the call may take no effect. Prefer the more stable [VPN config module (vpnconf)](/en/docs/handbook/vpnconf/index.md).

## Example

```lua
device.turn_off_vpn()
```

---

Source: [Convert GBK-encoded text to UTF-8 (string.from_gbk)](https://xxtouch.app/en/docs/handbook/ext-string/string.from_gbk.md)
Path: handbook/ext-string/string.from_gbk.md

# Convert GBK-encoded text to UTF-8 (string.from_gbk)

## Declaration

```lua
utf8_text = string.from_gbk(gbk_text)
```

## Parameters

- gbk_text
  string. GBK-encoded text to convert to UTF-8.

## Returns

- utf8_text
  string or nil. UTF-8 text. If conversion fails due to invalid encoding, returns nil.

## Description

> Convert GBK-encoded text to UTF-8. If the result looks garbled, the input might not be in GBK even though conversion succeeded.
> For more advanced conversions, see [luaiconv (iconv binding)](/en/docs/handbook/open-source/luaiconv.md).
> Note: GBK includes GB2312, so GB2312 can be converted with this function as well.

## Example

```lua
-- Chinese encoding GB2312 as subset of GBK
gbkstr = '\x58\x58\x54\x6f\x75\x63\x68\x20\xba\xdc\xc7\xbf'
--
sys.alert(gbkstr)                  -- GBK text can't be displayed
sys.alert(string.from_gbk(gbkstr)) -- "XXTouch 很强"
```
Note: Uses function outside of this chapter: [`sys.alert`](/en/docs/handbook/sys/sys.alert.md)
Explanation: In Lua string literals, "\xHH" denotes a single byte with hex value HH. For printable chars, see ASCII reference.

---

Source: [Split a path into components (file.path.components)](https://xxtouch.app/en/docs/handbook/file/file.path.components.md)
Path: handbook/file/file.path.components.md

# Split a path into components (file.path.components)


## Declaration

```lua
components, err = file.path.components(path)
```


## Parameters

- path
    String. The path string to split.


## Returns

- components
    Array (table) or nil. Returns an array of strings containing the path components on success, or nil if the path is invalid.
- err
    String. Returns `"Invalid path"` if the path is invalid.


## Description

> Split the path string into its components and return them in path order.
> The root directory `/` of an absolute path is returned as a separate component.
> **This function is available only in versions released after 20250914.**


## Example

```lua
local components = file.path.components("/usr/local/bin")
-- Returns {"/", "usr", "local", "bin"}
```

---

Source: [cv - Resize image to another size (:cv_resize)](https://xxtouch.app/en/docs/handbook/image/imagem_cv_resize.md)
Path: handbook/image/imagem_cv_resize.md

# cv - Resize image to another size (:cv_resize)

## Declaration

```lua
img = img:cv_resize(width, height)
```

## Parameters

- width, height
  Integer. New image dimensions

## Returns

- img
  Image object. Returns the image object itself with new size

## Description

> OpenCV extension: resize the image to new dimensions
> Mutates the image in-place

---

Source: [Check if VPN is on (device.is_vpn_on)](https://xxtouch.app/en/docs/handbook/device/device.is_vpn_on.md)
Path: handbook/device/device.is_vpn_on.md

# Check if VPN is on (device.is_vpn_on)

## Declaration

```lua
on, desc = device.is_vpn_on()
```

## Returns

- on
  Boolean. true when the VPN switch is on (connecting or already connected); false otherwise.
- desc
  String | nil. A description of the current VPN connection state when `on` is true.

## Description

> `on` also returns true while the VPN is connecting (not yet established).
> `desc` text may vary across locales and iOS versions, and is not guaranteed to be consistent.
> See the [VPN config module (vpnconf)](/en/docs/handbook/vpnconf/index.md) for more VPN features.

## Example

```lua
while true do
    local is_on, stat = device.is_vpn_on()
    if is_on then
        sys.toast(stat)
    else
        device.turn_on_vpn()
    end
end
```
Note: Uses function outside this chapter [`sys.toast`](/en/docs/handbook/sys/sys.toast.md)

---

Source: [Get the last path component (file.path.last_component)](https://xxtouch.app/en/docs/handbook/file/file.path.last_component.md)
Path: handbook/file/file.path.last_component.md

# Get the last path component (file.path.last_component)


## Declaration

```lua
last_component, err = file.path.last_component(path)
```


## Parameters

- path
    String. The path string.


## Returns

- last_component
    String or nil. Returns the last path component on success, or nil if the path is invalid.
- err
    String. Returns `"Invalid path"` if the path is invalid.


## Description

> Return the last path component. For the root directory `/`, return `/`.
> **This function is available only in versions released after 20250914.**


## Example

```lua
local last = file.path.last_component("/usr/local/bin") -- Returns "bin"
local root = file.path.last_component("/") -- Returns "/"
```

---

Source: [cv - Compare images (:cv_compare_image)](https://xxtouch.app/en/docs/handbook/image/imagem_cv_compare_image.md)
Path: handbook/image/imagem_cv_compare_image.md

# cv - Compare images (:cv_compare_image)

## Declaration

```lua
shapes, visualized = img:cv_compare_image(other_img[, options])
```

## Parameters

- other_img
  Image object. The image to compare with
- options
  Table
  <details>
  <summary>Option fields</summary>

  ```lua
  {
      should_visualize = false | true,  -- optional, whether to output visualization, default false
      approx_epsilon = integer_value,   -- optional, contour approximation percentage of perimeter, simplifies complex contours, default 2
  }
  ```
  </details>

## Returns

- shapes
  Table. The list of difference shapes between the two images
  <details>
  <summary>Shapes structure</summary>

  ```lua
  {
      { -- shape 1
          { -- vertex 1
              ["y"] = number_value,
              ["x"] = number_value,
          },
          { -- vertex 2
              ["y"] = number_value,
              ["x"] = number_value,
          },
          ...
      },
      { -- shape 2
          { -- vertex 1
              ["y"] = number_value,
              ["x"] = number_value,
          },
          { -- vertex 2
              ["y"] = number_value,
              ["x"] = number_value,
          },
          ...
      },
      ...
  }
  ```
  </details>
- visualized
  Image object. When options.should_visualize is true, this is the visualization image

## Description

Compare two images to find differences and return vertex lists of difference regions
The two images must have the same size

## Example

```lua
local cv = require("image.cv")
local img1 = image.load_file(XXT_SCRIPTS_PATH..'/1.png')
local img2 = image.load_file(XXT_SCRIPTS_PATH..'/2.png')
-- returns a list of shapes; may contain multiple shapes
local shapes, visimg = img1:cv_compare_image(img2)
nLog(shapes) -- print shapes
dialog():add_image(visimg):show() -- visualize difference image
```

---

Source: [Turn on flashlight (device.flash_on)](https://xxtouch.app/en/docs/handbook/device/device.flash_on.md)
Path: handbook/device/device.flash_on.md

# Turn on flashlight (device.flash_on)

## Declaration

```lua
ok = device.flash_on()
```

## Returns

- ok
  Boolean. true when the device has flashlight hardware and the camera is accessible; false otherwise.

## Description

> iPad Pro flashlight cannot be turned on
> Turns on the device flashlight. The flashlight is automatically turned off when the script terminates.

## Example

```lua
device.flash_on()
```

---

Source: [Remove the last path component (file.path.remove_last_component)](https://xxtouch.app/en/docs/handbook/file/file.path.remove_last_component.md)
Path: handbook/file/file.path.remove_last_component.md

# Remove the last path component (file.path.remove_last_component)


## Declaration

```lua
new_path, err = file.path.remove_last_component(path)
```


## Parameters

- path
    String. The original path string.


## Returns

- new_path
    String or nil. Returns the path string with its last component removed on success, or nil if the path is invalid.
- err
    String. Returns `"Invalid path"` if the path is invalid.


## Description

> Remove the last path component and return the new path.
> For `/usr`, return `/`; for the root directory `/`, return `/` unchanged.
> This function only processes the path string; it does not delete any actual file or directory.
> **This function is available only in versions released after 20250914.**


## Example

```lua
local parent = file.path.remove_last_component("/usr/local/bin") -- Returns "/usr/local"
local root = file.path.remove_last_component("/usr") -- Returns "/"
local unchanged = file.path.remove_last_component("/") -- Returns "/"
```

---

Source: [cv - Convert image to contour shapes (:cv_to_shapes)](https://xxtouch.app/en/docs/handbook/image/imagem_cv_to_shapes.md)
Path: handbook/image/imagem_cv_to_shapes.md

# cv - Convert image to contour shapes (:cv_to_shapes)

## Declaration

```lua
shapes, visualized = img:cv_to_shapes([ options ])
```

## Parameters

- options
  Optional, table
  <details>
  <summary>Option fields</summary>

  ```lua
  {
      should_visualize = false | true,  -- optional, whether to output visualization, default false
      closed = false | true,            -- optional, whether shapes are closed, default false
      blur_size = integer_value,        -- optional, blur kernel size, positive odd number only, default 3
      canny_threshold1 = 100,           -- optional, Canny lower threshold, default 100
      canny_threshold2 = 200,           -- optional, Canny upper threshold, default 200
      approx_epsilon = integer_value,   -- optional, contour approximation percentage of perimeter, default 2
  }
  ```
  </details>

## Returns

- shapes
  Table. List of shapes on the image
  <details>
  <summary>Shapes structure</summary>

  ```lua
  {
      { -- shape 1
          { -- vertex 1
              ["y"] = number_value,
              ["x"] = number_value,
          },
          { -- vertex 2
              ["y"] = number_value,
              ["x"] = number_value,
          },
          ...
      },
      { -- shape 2
          { -- vertex 1
              ["y"] = number_value,
              ["x"] = number_value,
          },
          { -- vertex 2
              ["y"] = number_value,
              ["x"] = number_value,
          },
          ...
      },
      ...
  }
  ```
  </details>
- visualized
  Image object. When options.should_visualize is true, this is the visualization image

## Description

Convert contours on the image into shapes (vertex lists)
Prefer simple, clear, closed shapes for better results

## Example

```lua
local cv = require("image.cv")
local img = image.load_file(XXT_SCRIPTS_PATH..'/1.png')
local shapes, visimg = img:cv_to_shapes({
    blur_size = 3,
    approx_epsilon = 2,
    closed = true,
    should_visualize = true,
})
nLog(shapes)
dialog():add_image(visimg):show()
```

---

Source: [Turn off flashlight (device.flash_off)](https://xxtouch.app/en/docs/handbook/device/device.flash_off.md)
Path: handbook/device/device.flash_off.md

# Turn off flashlight (device.flash_off)

## Declaration

```lua
ok = device.flash_off()
```

## Returns

- ok
  Boolean. true when the device has flashlight hardware and the camera is accessible; false otherwise.

## Description

> iPad Pro flashlight cannot be turned on
> If the flashlight is on, this function turns it off; otherwise does nothing

## Example

```lua
if device.flash_off() then
    -- device has flashlight
else
    -- device has no flashlight
end
```

---

Source: [Append a path component (file.path.add_component)](https://xxtouch.app/en/docs/handbook/file/file.path.add_component.md)
Path: handbook/file/file.path.add_component.md

# Append a path component (file.path.add_component)


## Declaration

```lua
new_path, err = file.path.add_component(path, component)
```


## Parameters

- path
    String. The base path string.
- component
    String. The path component to append.


## Returns

- new_path
    String or nil. Returns the path string with the component appended on success, or nil if the path or component is invalid.
- err
    String. Returns `"Invalid path"` if the path or component is invalid.


## Description

> Append the specified component to the base path, automatically handling the `/` separator at the join.
> This function only generates a path string; it does not create any actual file or directory.
> **This function is available only in versions released after 20250914.**


## Example

```lua
local full_path = file.path.add_component("/usr/local", "bin") -- Returns "/usr/local/bin"
local tmp_path = file.path.add_component("/", "tmp") -- Returns "/tmp"
```

---

Source: [cv - Find contours in image (:cv_find_shapes)](https://xxtouch.app/en/docs/handbook/image/imagem_cv_find_shapes.md)
Path: handbook/image/imagem_cv_find_shapes.md

# cv - Find contours in image (:cv_find_shapes)

## Declaration

```lua
found_shapes, visualized = img:cv_find_shapes(shapes[, options])
```

## Parameters

- shapes
  Table. One or more shapes' vertex info to search for
  <details>
  <summary>Shapes parameter structure</summary>

  ```lua
  {
      { -- shape 1
          { -- vertex 1
              ["y"] = number_value,
              ["x"] = number_value,
          },
          { -- vertex 2
              ["y"] = number_value,
              ["x"] = number_value,
          },
          ...
      },
      { -- shape 2
          { -- vertex 1
              ["y"] = number_value,
              ["x"] = number_value,
          },
          { -- vertex 2
              ["y"] = number_value,
              ["x"] = number_value,
          },
          ...
      },
      ...
  }
  ```
  </details>
- options
  Table, optional. Contour matching options
  <details>
  <summary>Option fields</summary>

  ```lua
  {
      should_visualize = false | true,  -- optional, whether to output visualization, default false
      closed = false | true,            -- optional, whether shapes are closed, default false
      min_area = number_value,          -- optional, minimum area, default -1 (no limit)
      max_area = number_value,          -- optional, maximum area, default -1 (no limit)
      blur_size = integer_value,        -- optional, blur kernel size, positive odd number only, default 3
      canny_threshold1 = 100,           -- optional, Canny lower threshold, default 100
      canny_threshold2 = 200,           -- optional, Canny upper threshold, default 200
      diff_threshold = number_value,    -- optional, difference threshold, smaller means more similar, default 0.001
      approx_epsilon = integer_value,   -- optional, contour approximation percentage of perimeter, default 2
  }
  ```
  </details>

## Returns

- found_shapes
  Table
  <details>
  <summary>Found shapes structure</summary>

  ```lua
  {
      { -- list of shapes matching input shape 1
          {
              diff_score = number_value, -- smaller is more similar
              { -- vertex 1
                  ["y"] = number_value,
                  ["x"] = number_value,
              },
              { -- vertex 2
                  ["y"] = number_value,
                  ["x"] = number_value,
              },
              ...
          },
          { -- second match for input shape 1
              diff_score = number_value,
              { -- vertex 1
                  ["y"] = number_value,
                  ["x"] = number_value,
              },
              { -- vertex 2
                  ["y"] = number_value,
                  ["x"] = number_value,
              },
              ...
          },
          ...
      },
      { -- list of shapes matching input shape 2
          { -- first match
              diff_score = number_value,
              { -- vertex 1
                  ["y"] = number_value,
                  ["x"] = number_value,
              },
              { -- vertex 2
                  ["y"] = number_value,
                  ["x"] = number_value,
              },
              ...
          },
          { -- second match
              diff_score = number_value,
              { -- vertex 1
                  ["y"] = number_value,
                  ["x"] = number_value,
              },
              { -- vertex 2
                  ["y"] = number_value,
                  ["x"] = number_value,
              },
              ...
          },
          ...
      },
      ...
  }
  ```
  </details>
- visualized
  Image object. When options.should_visualize is true, this is the visualization image

## Description

Find one or more shapes from an image
Standard regular shapes can be generated by functions

## Example

```lua
function make_triangle(side_len)
    local hf = math.sqrt(3)/2
    local h = math.floor(hf * side_len)
    return {
        { ["x"] = 1, ["y"] = h },
        { ["x"] = side_len, ["y"] = h },
        { ["x"] = side_len // 2, ["y"] = 1 },
    }
end

function make_rectangle(side_len)
    return {
        { ["x"] = 1, ["y"] = 1 },
        { ["x"] = 1, ["y"] = side_len },
        { ["x"] = side_len, ["y"] = side_len },
        { ["x"] = side_len, ["y"] = 1 },
    }
end

local info, visimg = screen.image():cv_find_shapes({make_triangle(45), make_rectangle(40)}, {
    min_area = 2000,
    max_area = 20000,
    diff_threshold = 0.005,
    approx_epsilon = 1,
    shape_match_mode = 3,
    closed = true,
    should_visualize = true,
})

nLog(info[1])
nLog(info[2])

dialog():add_image(visimg):show()
```

---

Source: [Turn on Reduce Motion (device.reduce_motion_on)](https://xxtouch.app/en/docs/handbook/device/device.reduce_motion_on.md)
Path: handbook/device/device.reduce_motion_on.md

# Turn on Reduce Motion (device.reduce_motion_on)

## Declaration

```lua
device.reduce_motion_on()
```

## Description

> The Reduce Motion switch is located at Settings → General → Accessibility → Reduce Motion on the device

## Example

```lua
device.reduce_motion_on()
```

---

Source: [Get the file extension of a path (file.path.extension)](https://xxtouch.app/en/docs/handbook/file/file.path.extension.md)
Path: handbook/file/file.path.extension.md

# Get the file extension of a path (file.path.extension)


## Declaration

```lua
extension, err = file.path.extension(path)
```


## Parameters

- path
    String. The path string.


## Returns

- extension
    String or nil. Returns the extension without the leading `.`, an empty string `""` if there is no extension, or nil if the path is invalid.
- err
    String. Returns `"Invalid path"` if the path is invalid.


## Description

> Return the file extension of the last path component. If there are multiple extension segments, return only the last one; for example, `archive.tar.gz` returns `gz`.
> **This function is available only in versions released after 20250914.**


## Example

```lua
local ext = file.path.extension("/path/to/file.txt") -- Returns "txt"
local archive_ext = file.path.extension("/path/to/archive.tar.gz") -- Returns "gz"
local no_ext = file.path.extension("/path/to/file") -- Returns ""
```

---

Source: [cv - Detect features of multiple templates (:cv_detect_templates)](https://xxtouch.app/en/docs/handbook/image/imagem_cv_detect_templates.md)
Path: handbook/image/imagem_cv_detect_templates.md

# cv - Detect features of multiple templates (:cv_detect_templates)

## Declaration

```lua
results, visualized = img:cv_detect_templates(templates_with_options)
```

## Parameters

- templates_with_options
  Optional, table. Each sequential element is an image object; named fields are options
  <details>
  <summary>Option fields</summary>

  ```lua
  {
      should_visualize = false | true,  -- optional, whether to output visualization, default false
      detector = 0 | 1 | 2,             -- optional, feature detector, 0: ORB, 1: SIFT, 2: SURF, default 0: ORB
      score_thresh = number_value,      -- optional, percent score threshold for feature matching, default 90
  }
  ```
  </details>

## Returns

- results
  Table. Collection of detected template features on the image
  <details>
  <summary>Result structure</summary>

  ```lua
  {
      { -- result 1
          { -- vertex 1
              ["y"] = number_value,
              ["x"] = number_value,
          },
          { -- vertex 2
              ["y"] = number_value,
              ["x"] = number_value,
          },
          { -- vertex 3
              ["y"] = number_value,
              ["x"] = number_value,
          },
          { -- vertex 4
              ["y"] = number_value,
              ["x"] = number_value,
          },
          confidence = number_value,  -- aggregated confidence of all feature points
          angle = number_value,       -- rotation angle
          index = number_value,       -- index of the matched template in the input collection
      },
      { -- result 2
          { -- vertex 1
              ["y"] = number_value,
              ["x"] = number_value,
          },
          { -- vertex 2
              ["y"] = number_value,
              ["x"] = number_value,
          },
          { -- vertex 3
              ["y"] = number_value,
              ["x"] = number_value,
          },
          { -- vertex 4
              ["y"] = number_value,
              ["x"] = number_value,
          },
          confidence = number_value,
          angle = number_value,
          index = number_value,
      },
      ...
  }
  ```
  </details>
- visualized
  Image object. When options.should_visualize is true, this is the visualization image

## Description

Detect features on the image from a set of small image templates; works with transformed/rotated templates
Each template only returns the best result whose score exceeds score_thresh
**`Supported in versions >= 20250625`**

## Note

score_thresh (input) differs from confidence (output)
score_thresh filters feature points; confidence is aggregated template confidence

## Example

```lua
local cv = require("image.cv")
local img1 = image.load_file(XXT_SCRIPTS_PATH..'/1.png')
local img2 = image.load_file(XXT_SCRIPTS_PATH..'/2.png')

local results, visimg = screen.image():cv_detect_templates({
    img1, img2;
    score_thresh = 90,
    detector = 1, -- SIFT
    should_visualize = true, -- when true, second return value is an image
})

nLog(results)
dialog():add_image(visimg):show()
```

---

Source: [Turn off Reduce Motion (device.reduce_motion_off)](https://xxtouch.app/en/docs/handbook/device/device.reduce_motion_off.md)
Path: handbook/device/device.reduce_motion_off.md

# Turn off Reduce Motion (device.reduce_motion_off)

## Declaration

```lua
device.reduce_motion_off()
```

## Description

> The Reduce Motion switch is located at Settings → General → Accessibility → Reduce Motion on the device

## Example

```lua
device.reduce_motion_off()
```

---

Source: [Remove the file extension from a path (file.path.remove_extension)](https://xxtouch.app/en/docs/handbook/file/file.path.remove_extension.md)
Path: handbook/file/file.path.remove_extension.md

# Remove the file extension from a path (file.path.remove_extension)


## Declaration

```lua
new_path, err = file.path.remove_extension(path)
```


## Parameters

- path
    String. The original path string.


## Returns

- new_path
    String or nil. Returns the path string with its extension removed on success, or nil if the path is invalid.
- err
    String. Returns `"Invalid path"` if the path is invalid.


## Description

> Remove the extension and its preceding `.` from the last path component. If there are multiple extension segments, remove only the last one; if there is no extension, return the original path.
> This function only processes the path string; it does not rename any actual file or directory.
> **This function is available only in versions released after 20250914.**


## Example

```lua
local base = file.path.remove_extension("/path/to/file.txt") -- Returns "/path/to/file"
local archive_base = file.path.remove_extension("/path/to/archive.tar.gz") -- Returns "/path/to/archive.tar"
local unchanged = file.path.remove_extension("/path/to/file") -- Returns "/path/to/file"
```

---

Source: [Turn on AssistiveTouch (device.assistive_touch_on)](https://xxtouch.app/en/docs/handbook/device/device.assistive_touch_on.md)
Path: handbook/device/device.assistive_touch_on.md

# Turn on AssistiveTouch (device.assistive_touch_on)

## Declaration

```lua
device.assistive_touch_on()
```

## Description

> The AssistiveTouch switch is located at Settings → General → Accessibility → AssistiveTouch on the device

## Example

```lua
device.assistive_touch_on()
```

---

Source: [Append a file extension (file.path.add_extension)](https://xxtouch.app/en/docs/handbook/file/file.path.add_extension.md)
Path: handbook/file/file.path.add_extension.md

# Append a file extension (file.path.add_extension)


## Declaration

```lua
new_path, err = file.path.add_extension(path, extension)
```


## Parameters

- path
    String. The base path string.
- extension
    String. The file extension to append, usually without a leading `.`.


## Returns

- new_path
    String or nil. Returns the path string with the extension appended on success, or nil if it cannot be appended.
- err
    String. Returns `"Invalid path"` if the path string is invalid, or `"Invalid extension"` if the extension string is invalid. If the extension cannot be appended, for example because it contains `/`, the function may return only nil without an error message.


## Description

> Append `.` and the specified extension to the path. If the path already has an extension, append the new extension after it; for example, appending `bak` to `file.txt` produces `file.txt.bak`.
> The supplied extension may contain a leading `.`, but this function does not remove it; passing `.txt` appends `..txt`.
> This function only generates a path string; it does not rename any actual file or directory.
> **This function is available only in versions released after 20250914.**


## Example

```lua
local new_path = file.path.add_extension("/path/to/file", "txt") -- Returns "/path/to/file.txt"
local archive_path = file.path.add_extension("/path/to/file.tar", "gz") -- Returns "/path/to/file.tar.gz"
local backup_path = file.path.add_extension("/path/to/file.txt", "bak") -- Returns "/path/to/file.txt.bak"
local dotted_path = file.path.add_extension("/path/to/file", ".txt") -- Returns "/path/to/file..txt"
```

---

Source: [Turn off AssistiveTouch (device.assistive_touch_off)](https://xxtouch.app/en/docs/handbook/device/device.assistive_touch_off.md)
Path: handbook/device/device.assistive_touch_off.md

# Turn off AssistiveTouch (device.assistive_touch_off)

## Declaration

```lua
device.assistive_touch_off()
```

## Description

> The AssistiveTouch switch is located at Settings → General → Accessibility → AssistiveTouch on the device

## Example

```lua
device.assistive_touch_off()
```

---

Source: [Normalize a path (file.path.normalize)](https://xxtouch.app/en/docs/handbook/file/file.path.normalize.md)
Path: handbook/file/file.path.normalize.md

# Normalize a path (file.path.normalize)


## Declaration

```lua
normalized_path, err = file.path.normalize(path)
```


## Parameters

- path
    String. The original path string.


## Returns

- normalized_path
    String or nil. Returns the normalized path string on success, or nil if the path is invalid.
- err
    String. Returns `"Invalid path"` if the path is invalid.


## Description

> Normalize the path by processing its `.` and `..` components and removing redundant slashes.
> To resolve symbolic links in a path, use [`file.path.resolve_symlinks`](file.path.resolve_symlinks.md).
> This function does not move or rename any actual file or directory.
> **This function is available only in versions released after 20250914.**


## Example

```lua
local std_path = file.path.normalize("/usr/local/../bin/./script") -- Returns "/usr/bin/script"
local clean_path = file.path.normalize("//tmp///file/") -- Returns "/tmp/file"
```

---

Source: [Get backlight brightness (device.brightness)](https://xxtouch.app/en/docs/handbook/device/device.brightness.md)
Path: handbook/device/device.brightness.md

# Get backlight brightness (device.brightness)

## Declaration

```lua
brightness = device.brightness()
```

## Returns

- brightness
  Number. Current device backlight brightness in the range 0.0 ~ 1.0

## Example

See the example in [`device.set_brightness`](/en/docs/handbook/device/device.set_brightness.md).

---

Source: [Resolve symbolic links in a path (file.path.resolve_symlinks)](https://xxtouch.app/en/docs/handbook/file/file.path.resolve_symlinks.md)
Path: handbook/file/file.path.resolve_symlinks.md

# Resolve symbolic links in a path (file.path.resolve_symlinks)


## Declaration

```lua
resolved_path, err = file.path.resolve_symlinks(path)
```


## Parameters

- path
    String. The original path string containing symbolic links.


## Returns

- resolved_path
    String or nil. Returns the path string with symbolic links resolved and the path normalized on success, or nil if the path string is invalid.
- err
    String. Returns `"Invalid path"` if the path is invalid.


## Description

> Resolve symbolic links in the path and normalize the resulting path. The result depends on the actual symbolic links on the device.
> Returning a path string does not mean the path necessarily exists. If the path does not exist or contains parts that cannot be resolved, nil or an error message is not guaranteed. To check whether it exists, use [`file.exists`](file.exists.md).
> **This function is available only in versions released after 20250914.**


## Example

```lua
-- Assume /var/mobile/link is a symbolic link to /var/mobile/Documents
local real_path = file.path.resolve_symlinks("/var/mobile/link/script.lua")
-- Returns "/var/mobile/Documents/script.lua"
```

---

Source: [Set screen brightness (device.set_brightness)](https://xxtouch.app/en/docs/handbook/device/device.set_brightness.md)
Path: handbook/device/device.set_brightness.md

# Set screen brightness (device.set_brightness)

## Declaration

```lua
device.set_brightness(val)
```

## Parameters

- val
  Number. Set device backlight brightness, range 0.0 ~ 1.0

## Description

> This call will turn off system auto-brightness adjustment

## Example

```lua
sys.toast(device.brightness())
for i = 1, 10 do
    device.set_brightness(i/10)
    sys.msleep(200)
end
for i = 10, 5, -1 do
    device.set_brightness(i/10)
    sys.msleep(200)
end
```
Note: Uses functions outside this chapter [`sys.toast`](/en/docs/handbook/sys/sys.toast.md), [`sys.msleep`](/en/docs/handbook/sys/sys.msleep.md)

---

Source: [Set auto-lock minutes (device.set_autolock_time)](https://xxtouch.app/en/docs/handbook/device/device.set_autolock_time.md)
Path: handbook/device/device.set_autolock_time.md

# Set auto-lock minutes (device.set_autolock_time)

## Declaration

```lua
device.set_autolock_time(minutes)
```

## Parameters

- minutes
  Integer. Set device auto-lock minutes. 0 means never auto-lock

## Description

> Only intervals offered by the system are accepted (the options shown under **Settings → Display & Brightness → Auto-Lock**)

## Example

```lua
device.set_autolock_time(0)
```

---

Source: [Compute MD5 hash of string (string.md5)](https://xxtouch.app/en/docs/handbook/ext-string/string.md5.md)
Path: handbook/ext-string/string.md5.md

# Compute MD5 hash of string (string.md5)

## Declaration

```lua
hash = string.md5(data)
```

## Parameters

- data
  string. Original string (or binary data).

## Returns

- hash
  string. Hex text of the MD5 digest.

## Description

> Compute MD5 checksum of a string (or binary data).

## Example

```lua
sys.alert(string.md5('XXTouch 真棒')) -- "4921dbf380df452fa959dc47cef30e4b"
```
Note: Uses function outside of this chapter: [`sys.alert`](/en/docs/handbook/sys/sys.alert.md)

## More examples

[At the end of this chapter](/en/docs/handbook/ext-string/samples.md)

---

Source: [Set device volume (device.set_volume)](https://xxtouch.app/en/docs/handbook/device/device.set_volume.md)
Path: handbook/device/device.set_volume.md

# Set device volume (device.set_volume)

## Declaration

```lua
device.set_volume(val)
```

## Parameters

- val
  Number. Volume value in range 0.0 ~ 1.0

## Example

```lua
device.set_volume(0) -- mute
```

---

Source: [! Join a Wi‑Fi network (device.join_wifi)](https://xxtouch.app/en/docs/handbook/device/device.join_wifi.md)
Path: handbook/device/device.join_wifi.md

# ! Join a Wi‑Fi network (device.join_wifi)

## Declaration

```lua
ok, err = device.join_wifi(SSID, password[, timeout_ms])
```

## Parameters

- SSID
  String. Wi‑Fi SSID (name)
- password
  String. Wi‑Fi password
- timeout_ms
  Integer, optional. Timeout in milliseconds. Default 10000

## Returns

- ok
  Boolean. true if operation succeeded; otherwise false
- err
  String. Error message when operation failed

## Description

> **This function becomes synchronous in versions after 20250317**

## Example

```lua
local ok, err = device.join_wifi('Tenda_9B3F', '12345678')
```

---

Source: [Forget a Wi‑Fi network (device.forget_wifi)](https://xxtouch.app/en/docs/handbook/device/device.forget_wifi.md)
Path: handbook/device/device.forget_wifi.md

# Forget a Wi‑Fi network (device.forget_wifi)

## Declaration

```lua
ok = device.forget_wifi(SSID)
```

## Parameters

- SSID
  String. Wi‑Fi SSID (name) to forget

## Returns

- ok
  Boolean. true if removed from the saved Wi‑Fi list; otherwise false

## Example

```lua
local ok = device.forget_wifi('Tenda_9B3F')
```

---

Source: [Compute SHA1 hash of string (string.sha1)](https://xxtouch.app/en/docs/handbook/ext-string/string.sha1.md)
Path: handbook/ext-string/string.sha1.md

# Compute SHA1 hash of string (string.sha1)

## Declaration

```lua
hash = string.sha1(data)
```

## Parameters

- data
  string. Original string (or binary data).

## Returns

- hash
  string. Hex text of the SHA1 digest.

## Description

> Compute SHA1 checksum of a string (or binary data).

## Example

```lua
sys.alert(string.sha1('XXTouch 真棒')) -- "a959c48d904c1075c7ddfdb1fda49effb2142493"
```
Note: Uses function outside of this chapter: [`sys.alert`](/en/docs/handbook/sys/sys.alert.md)

## More examples

[At the end of this chapter](/en/docs/handbook/ext-string/samples.md)

---

Source: [Compute HMAC-SHA1 hash (string.hmac_sha1)](https://xxtouch.app/en/docs/handbook/ext-string/string.hmac_sha1.md)
Path: handbook/ext-string/string.hmac_sha1.md

# Compute HMAC-SHA1 hash (string.hmac_sha1)

## Declaration

```lua
hex_hash = string.hmac_sha1(data, key)
```

## Parameters

- data
  string. Input data to hash.
- key
  string. Secret key used by the HMAC algorithm.

## Returns

- hex_hash
  string. Lowercase hex text of the HMAC-SHA1 digest.

## Description

> Use the HMAC-SHA1 algorithm to compute a keyed hash for any string (or binary data).

## Example

```lua
local signature = string.hmac_sha1('hello world', 'secret')
sys.alert(signature) -- prints "03376ee7ad7bbfceee98660439a4d8b125122a5a"
```
Note: Uses function outside of this chapter: [`sys.alert`](/en/docs/handbook/sys/sys.alert.md)

---

Source: [Compute HMAC-SHA256 hash (string.hmac_sha256)](https://xxtouch.app/en/docs/handbook/ext-string/string.hmac_sha256.md)
Path: handbook/ext-string/string.hmac_sha256.md

# Compute HMAC-SHA256 hash (string.hmac_sha256)

## Declaration

```lua
hex_hash = string.hmac_sha256(data, key)
```

## Parameters

- data
  string. Input data to hash.
- key
  string. Secret key used by the HMAC algorithm.

## Returns

- hex_hash
  string. Lowercase hex text of the HMAC-SHA256 digest.

## Description

> Use the HMAC-SHA256 algorithm to compute a keyed hash for any string (or binary data).

## Example

```lua
local signature = string.hmac_sha256('hello world', 'secret')
sys.alert(signature) -- prints "734cc62f32841568f45715aeb9f4d7891324e6d948e4c6c60c0621cdac48623a"
```
Note: Uses function outside of this chapter: [`sys.alert`](/en/docs/handbook/sys/sys.alert.md)

---

Source: [Base64-encode string (string.base64_encode)](https://xxtouch.app/en/docs/handbook/ext-string/string.base64_encode.md)
Path: handbook/ext-string/string.base64_encode.md

# Base64-encode string (string.base64_encode)

## Declaration

```lua
b64 = string.base64_encode(data)
```

## Parameters

- data
  string. Original string (or binary data).

## Returns

- b64
  string. Base64-encoded text.

## Description

> Base64-encode a string (or binary data).
> Keywords: image Base64, file Base64, data Base64, binary Base64

## Example

```lua
-- Capture a screen region as png, then base64-encode
b64s = screen.image(0, 0, 100, 100):png_data():base64_encode()

-- Read a file then base64-encode
b64s = file.reads('/var/mobile/1.png'):base64_encode()
```
Note: Uses functions outside of this chapter: [`screen.image`](/en/docs/handbook/screen/screen.image.md), [`:png_data`](/en/docs/handbook/image/imagem_png_data.md), [`file.reads`](/en/docs/handbook/file/file.reads.md)

## More examples

[At the end of this chapter](/en/docs/handbook/ext-string/samples.md)

---

Source: [Decode Base64 string (string.base64_decode)](https://xxtouch.app/en/docs/handbook/ext-string/string.base64_decode.md)
Path: handbook/ext-string/string.base64_decode.md

# Decode Base64 string (string.base64_decode)

## Declaration

```lua
data = string.base64_decode(b64)
```

## Parameters

- b64
  string. Base64-encoded text.

## Returns

- data
  string. Decoded string (or binary data).

## Description

> Inverse of string.base64_encode. Convert Base64 text back to string (or binary data).

## Example

[At the end of this chapter](/en/docs/handbook/ext-string/samples.md)

---

Source: [Encode a URI (string.encode_uri)](https://xxtouch.app/en/docs/handbook/ext-string/string.encode_uri.md)
Path: handbook/ext-string/string.encode_uri.md

# Encode a URI (string.encode_uri)

## Declaration

```lua
encoded = string.encode_uri(uri)
```

## Parameters

- uri
  string. The URI string.

## Returns

- encoded
  string. Encoded URI.

## Description

> Percent-encode a URI string (escape special characters).
> Keywords: URL encode, URI encode
> Available in versions after 2025-03-13

## Example

```lua
nLog(string.encode_uri("https://www.example.com/测试")) -- https://www.example.com/%E6%B5%8B%E8%AF%95
```

---

Source: [Decode a URI (string.decode_uri)](https://xxtouch.app/en/docs/handbook/ext-string/string.decode_uri.md)
Path: handbook/ext-string/string.decode_uri.md

# Decode a URI (string.decode_uri)

## Declaration

```lua
uri = string.decode_uri(encoded)
```

## Parameters

- encoded
  string. Encoded URI string.

## Returns

- uri
  string. Decoded URI.

## Description

> Inverse of string.encode_uri. Decode a percent-encoded URI string.
> Keywords: URL decode, URI decode
> Available in versions after 2025-03-13

## Example

```lua
nLog(string.decode_uri("https://www.example.com/%E6%B5%8B%E8%AF%95")) -- https://www.example.com/测试
```

---

Source: [Encode a URI component (string.encode_uri_component)](https://xxtouch.app/en/docs/handbook/ext-string/string.encode_uri_component.md)
Path: handbook/ext-string/string.encode_uri_component.md

# Encode a URI component (string.encode_uri_component)

## Declaration

```lua
encoded_component = string.encode_uri_component(component)
```

## Parameters

- component
  string. The URI component string.

## Returns

- encoded_component
  string. Encoded URI component.

## Description

> Percent-encode a URI component (escape special characters).
> Keywords: URI component encode
> Available in versions after 2025-03-13

## Example

```lua
nLog(string.encode_uri_component("https://www.example.com/测试")) -- https%3A%2F%2Fwww.example.com%2F%E6%B5%8B%E8%AF%95
```

---

Source: [Decode a URI component (string.decode_uri_component)](https://xxtouch.app/en/docs/handbook/ext-string/string.decode_uri_component.md)
Path: handbook/ext-string/string.decode_uri_component.md

# Decode a URI component (string.decode_uri_component)

## Declaration

```lua
component = string.decode_uri_component(encoded_component)
```

## Parameters

- encoded_component
  string. Encoded URI component.

## Returns

- component
  string. Decoded URI component string.

## Description

> Inverse of string.encode_uri_component. Decode a percent-encoded URI component.
> Keywords: URI component decode
> Available in versions after 2025-03-13

## Example

```lua
nLog(string.decode_uri_component("https://www.example.com/%E6%B5%8B%E8%AF%95")) -- https://www.example.com/测试
```

---

Source: [Encrypt a string (string.aes128_encrypt)](https://xxtouch.app/en/docs/handbook/ext-string/string.aes128_encrypt.md)
Path: handbook/ext-string/string.aes128_encrypt.md

# Encrypt a string (string.aes128_encrypt)

> **Deprecated:** This function is kept only for compatibility with existing scripts. For new scripts, use [lua-openssl](../open-source/lua-openssl.md) and choose an algorithm such as `aes-128-ecb` or `aes-128-gcm`.

## Declaration

```lua
encrypted = string.aes128_encrypt(data, key)
```

## Parameters

- data
  string. The original string (or binary data) to encrypt.
- key
  string. The password.

## Returns

- encrypted
  string. Encrypted binary data.

## Description

> Encrypt a string (or binary data) using AES128 algorithm in ECB mode.
> Note: AES128 ECB mode has no iv (initialization vector). If an integration requires an iv field, use 0.

## Example

[At the end of this chapter](/en/docs/handbook/ext-string/samples.md)

---

Source: [Decrypt an encrypted string (string.aes128_decrypt)](https://xxtouch.app/en/docs/handbook/ext-string/string.aes128_decrypt.md)
Path: handbook/ext-string/string.aes128_decrypt.md

# Decrypt an encrypted string (string.aes128_decrypt)

> **Deprecated:** This function is kept only for compatibility with existing scripts. For new scripts, use [lua-openssl](../open-source/lua-openssl.md) and choose an algorithm such as `aes-128-ecb` or `aes-128-gcm`.

## Declaration

```lua
data = string.aes128_decrypt(encrypted, key)
```

## Parameters

- encrypted
  string. Encrypted string (or binary data).
- key
  string. The password.

## Returns

- data
  string. Decrypted string (or binary data).

## Description

> Decrypt data encrypted by AES128 algorithm in ECB mode.
> Note: AES128 ECB mode has no iv (initialization vector). If an integration requires an iv field, use 0.

## Example

[At the end of this chapter](/en/docs/handbook/ext-string/samples.md)

---

Source: [Split a string by separator rule (string.split)](https://xxtouch.app/en/docs/handbook/ext-string/string.split.md)
Path: handbook/ext-string/string.split.md

# Split a string by separator rule (string.split)

## Declaration

```lua
parts = string.split(text, sep)
```

## Parameters

- text
  string. Text to split.
- sep
  string. Separator string.

## Returns

- parts
  table. Array of split segments in order.

## Description

> Split a string by a separator rule.
> Keywords: split string, split text.

## Examples

```lua
-- Example 1 (split account/password):
t = string.split('lfue6841214----123456', '----')
sys.alert('Account: '..t[1])
--
-- Example 2 (get text between two # marks):
t = string.split('Hello, your verification code is #4937#, valid for 15 minutes. [ACME Corp]', '#')
sys.alert('Code: '..t[2])
--
-- Example 3 (a more complex middle extraction):
t = string.split('Hello, your code is 4937, valid for 15 minutes. [ACME Corp]', 'code is ')
t = string.split(t[2], ', valid')
sys.alert('Code: '..t[1])
```
Note: Uses function outside of this chapter: [`sys.alert`](/en/docs/handbook/sys/sys.alert.md)

## Wrapper example 1

```lua
-- Extract middle text (return nil if not found)
function str_middle(str, sep1, sep2)
    assert(type(str) == 'string', '`str_middle` #1 must be string')
    assert(type(sep1) == 'string', '`str_middle` #2 must be string')
    assert(type(sep2) == 'nil' or type(sep2) == 'string', '`str_middle` #3 optional but must be string')
    local t = string.split(str, sep1)
    if not sep2 or sep1==sep2 then
        return t[2]
    else
        if t[2] == nil then
            return nil
        else
            t = string.split(t[2], sep2)
            if t[2] == nil then
                return nil
            else
                return t[1]
            end
        end
    end
end
--
r = str_middle('Hello, your code is 4937, valid for 15 minutes. [ACME Corp]', 'is ', ', valid')
sys.alert('Code: '..r)
-- "4937"
--
r = str_middle('Hello, your verification code is #8346#, valid for 15 minutes. [ACME Corp]', '#')
sys.alert('Code: '..r)
-- "8346"
```
Note: Uses function outside of this chapter: [`sys.alert`](/en/docs/handbook/sys/sys.alert.md)

## Wrapper example 2

```lua
-- basename
function str_strip_dirname(path)
    local d = string.split(path, '/')
    return d[#d]
end

-- dirname
function str_strip_filename(path)
    local d = string.split(path, '/')
    d[#d] = nil
    return table.concat(d, '/')
end

-- strip extension of last path segment
function str_strip_extension(path)
    local d = string.split(path, '/')
    local fnt = string.split(d[#d], '.')
    d[#d] = fnt[1]
    return table.concat(d, '/')
end

-- get extension(s) of last path segment
function str_get_extension(path)
    local d = string.split(path, '/')
    local fnt = string.split(d[#d], '.')
    table.remove(fnt, 1)
    return table.concat(fnt, '.')
end

sys.alert(str_strip_dirname("/private/var/mobile/Media/1ferver/lua/scripts/1.lua.xxt"))
-- "1.lua.xxt"

sys.alert(str_strip_filename("/private/var/mobile/Media/1ferver/lua/scripts/1.lua.xxt"))
-- "/private/var/mobile/Media/1ferver/lua/scripts"

sys.alert(str_strip_extension("/private/var/mobile/Media/1ferver/lua/scripts/1.lua.xxt"))
-- "/private/var/mobile/Media/1ferver/lua/scripts/1"

sys.alert(str_get_extension("/private/var/mobile/Media/1ferver/lua/scripts/1.lua.xxt"))
-- "lua.xxt"

sys.alert(str_strip_extension(str_strip_dirname("/private/var/mobile/Media/1ferver/lua/scripts/1.lua.xxt")))
-- "1"
```
Note: Uses functions outside of this chapter: [`sys.alert`](/en/docs/handbook/sys/sys.alert.md), [table.concat](https://www.lua.org/manual/5.3/manual.html#pdf-table.concat)

## Possibly related example (explode mixed Chinese/English UTF-8 string into characters, UTF-8 only)

```lua
-- Not an example using string.split
function text_explode(text)
    local ret = {}
    for p, c in utf8.codes(text) do
        ret[#ret + 1] = utf8.char(c)
    end
    return ret
end
--
local t = text_explode('你好，XXTouch')
sys.alert(table.concat(t, '/')) -- "你/好/，/X/X/T/o/u/c/h"
```
Note: Uses functions outside of this chapter: [`sys.alert`](/en/docs/handbook/sys/sys.alert.md), [table.concat](https://www.lua.org/manual/5.3/manual.html#pdf-table.concat), [utf8.char](https://www.lua.org/manual/5.3/manual.html#pdf-utf8.char), [utf8.codes](https://www.lua.org/manual/5.3/manual.html#pdf-utf8.codes)

## More examples

[At the end of this chapter](/en/docs/handbook/ext-string/samples.md)

---

Source: [Trim leading whitespace (string.ltrim)](https://xxtouch.app/en/docs/handbook/ext-string/string.ltrim.md)
Path: handbook/ext-string/string.ltrim.md

# Trim leading whitespace (string.ltrim)

## Declaration

```lua
out = string.ltrim(text)
```

## Parameters

- text
  string. Text to trim.

## Returns

- out
  string. The text with leading whitespace removed.

## Description

> Remove leading whitespace characters.
> Whitespace includes "\r" "\n" "\t".

## Example

[At the end of this chapter](/en/docs/handbook/ext-string/samples.md)

---

Source: [Trim trailing whitespace (string.rtrim)](https://xxtouch.app/en/docs/handbook/ext-string/string.rtrim.md)
Path: handbook/ext-string/string.rtrim.md

# Trim trailing whitespace (string.rtrim)

## Declaration

```lua
out = string.rtrim(text)
```

## Parameters

- text
  string. Text to trim.

## Returns

- out
  string. The text with trailing whitespace removed.

## Description

> Remove trailing whitespace characters.
> Whitespace includes "\r" "\n" "\t".

## Example

[At the end of this chapter](/en/docs/handbook/ext-string/samples.md)

---

Source: [Trim both ends (string.trim)](https://xxtouch.app/en/docs/handbook/ext-string/string.trim.md)
Path: handbook/ext-string/string.trim.md

# Trim both ends (string.trim)

## Declaration

```lua
out = string.trim(text)
```

## Parameters

- text
  string. Text to trim.

## Returns

- out
  string. The text with leading and trailing whitespace removed.

## Description

> Remove whitespace on both ends.
> Whitespace includes "\r" "\n" "\t".

## Example

[At the end of this chapter](/en/docs/handbook/ext-string/samples.md)

---

Source: [Remove all whitespace in text (string.atrim)](https://xxtouch.app/en/docs/handbook/ext-string/string.atrim.md)
Path: handbook/ext-string/string.atrim.md

# Remove all whitespace in text (string.atrim)

## Declaration

```lua
out = string.atrim(text)
```

## Parameters

- text
  string. Text to process.

## Returns

- out
  string. The text with all whitespace removed.

## Description

> Remove all whitespace characters from the text.
> Whitespace includes "\r" "\n" "\t".

## Example

[At the end of this chapter](/en/docs/handbook/ext-string/samples.md)

---

Source: [Strip UTF-8 BOM from beginning (string.strip_utf8_bom)](https://xxtouch.app/en/docs/handbook/ext-string/string.strip_utf8_bom.md)
Path: handbook/ext-string/string.strip_utf8_bom.md

# Strip UTF-8 BOM from beginning (string.strip_utf8_bom)

## Declaration

```lua
out = string.strip_utf8_bom(text)
```

## Parameters

- text
  string. Text that may contain UTF-8 BOM.

## Returns

- out
  string. Text with BOM removed.

## Description

> UTF-8 BOM appears as three invisible bytes at file start: "\xEF\xBB\xBF"  (In Lua string literals, "\\x" followed by two hex digits denotes a single byte; e.g., "\\x58" is 'X'. See ASCII reference.)

## Example

```lua
txt = "\xEF\xBB\xBFXXTouch"
sys.alert(txt..', '..#txt) -- "XXTouch, 10"
--
txt = string.strip_utf8_bom(txt)
sys.alert(txt..', '..#txt) -- "XXTouch, 7"
```
Note: Uses function outside of this chapter: [`sys.alert`](/en/docs/handbook/sys/sys.alert.md)

## Tips

> UTF-8 does not require a BOM, although Unicode allows it. Non-BOM UTF-8 is standard; putting BOM in UTF-8 files is mainly a Windows practice and may cause issues elsewhere.

---

Source: [Generate a random string (string.random)](https://xxtouch.app/en/docs/handbook/ext-string/string.random.md)
Path: handbook/ext-string/string.random.md

# Generate a random string (string.random)

## Declaration

```lua
rs = string.random(pool [, count, bytes_per_char ])
```

## Parameters

- pool
  string. Character dictionary to pick from.
- count
  integer, optional. Number of characters to generate. Default 6.
- bytes_per_char
  integer, optional. Number of bytes per character. Default 1.

## Returns

- rs
  string. Generated random string.

## Description

> Generate a random string. Note: each Chinese character in UTF-8 is 3 bytes.

## Example

```lua
rs = string.random("qwertyuiopasdfghjklzxcvbnm", 20, 1)
rs = string.random("一二三四五六七八九十", 20, 3)
```

---

Source: [Compare two version strings (string.compare_version)](https://xxtouch.app/en/docs/handbook/ext-string/string.compare_version.md)
Path: handbook/ext-string/string.compare_version.md

# Compare two version strings (string.compare_version)

## Declaration

```lua
cmp = string.compare_version(ver_a, ver_b)
```

## Parameters

- ver_a, ver_b
  string. Versions to compare.

## Returns

- cmp
  integer. 1 if ver_a `>` ver_b, -1 if ver_a `<` ver_b, 0 if equal.

## Description

> Compare two version strings using rules:
> - Split by '.' or '-' or spaces as numeric segments (multiple separators collapse as one)
> - Higher weight to left-most segments
> - Stop at first illegal character
> - Pad missing segments with '0'
> - Empty or illegal strings are treated as '0'
> - Examples: '1.1' == '1.1.0' == '1-1'; '1.0' == '1 0'; '1.0' > '0.99999'
> - Usable in XUI

## Examples

```lua
-- "1.5", "1.05", and "1.005" are the same version
-- "1.5", "1.50", and "1.500" are three different versions
-- "1.11" is greater than "1.5"
-- "1.52" is equal to "1.52.0"
assert(string.compare_version("", "") == 0)
assert(string.compare_version("1", "") == 1)
assert(string.compare_version("", "1") == -1)
assert(string.compare_version("1", "1") == 0)
assert(string.compare_version("1.0", "1") == 0)
assert(string.compare_version("1", "1.0") == 0)
assert(string.compare_version("1.", "1") == 0)
assert(string.compare_version("1", "1.") == 0)
assert(string.compare_version("1.", "1.0") == 0)
assert(string.compare_version("1.0", "1.") == 0)
assert(string.compare_version("1.0", "1.0") == 0)
assert(string.compare_version("1.0.0", "1.0.0") == 0)

-- Greater / less examples
assert(string.compare_version("1.1", "1.0") == 1)
assert(string.compare_version("1.0", "1.1") == -1)
assert(string.compare_version("1.1", "1.10") == -1)
assert(string.compare_version("1.2", "1.11") == -1)
assert(string.compare_version("1.1", "1.1.1") == -1)
assert(string.compare_version("1.2", "1.1.1") == 1)
assert(string.compare_version("1.0", "0.99999") == 1)
assert(string.compare_version("1.10.1", "1.10") == 1)
assert(string.compare_version("1.2-4", "1.2-3") == 1)
assert(string.compare_version("1.2-3", "1.2.3") == 0)
assert(string.compare_version("1.2-4", "1.2.3.0") == 1)
assert(string.compare_version("1.2-4", "1.2.3.10") == 1)
assert(string.compare_version("1.2-4", "1.2.30.10") == -1)
assert(string.compare_version("1.2-3", "1.2.4") == -1)
assert(string.compare_version("2.2", "1.2") == 1)
assert(string.compare_version("2.2", "10.2") == -1)
assert(string.compare_version("2..2", "2.2") == 0)
assert(string.compare_version("2.2.x.3", "2.2") == 0)
assert(string.compare_version("x", "") == 0)
```

---

Source: [Check if a string starts with (string.starts_with)](https://xxtouch.app/en/docs/handbook/ext-string/string.starts_with.md)
Path: handbook/ext-string/string.starts_with.md

# Check if a string starts with (string.starts_with)

## Declaration

```lua
ok = string.starts_with(text, prefix[, pos])
```

## Parameters

- text
  string.
- prefix
  string.
- pos
  integer, optional. Start position, default 1.

## Returns

- ok
  boolean.

## Description

> Check whether `text` starts with `prefix`.
> Available in versions after 2025-03-13

## Example

```lua
nLog(string.starts_with('Hello, XXTouch', 'Hello')) -- true
nLog(string.starts_with('Hello, XXTouch', 'ello', 2)) -- true
```
Note: Uses function outside of this chapter: [`nLog`](/en/docs/handbook/develop-helper/nLog.md)

---

Source: [Check if a string ends with (string.ends_with)](https://xxtouch.app/en/docs/handbook/ext-string/string.ends_with.md)
Path: handbook/ext-string/string.ends_with.md

# Check if a string ends with (string.ends_with)

## Declaration

```lua
ok = string.ends_with(text, suffix[, len])
```

## Parameters

- text
  string.
- suffix
  string.
- len
  integer, optional. Length to consider for search. Default: length of `text`.

## Returns

- ok
  boolean.

## Description

> Check whether `text` ends with `suffix`.
> Available in versions after 2025-03-13

## Example

```lua
nLog(string.ends_with('Hello, XXTouch', 'XXTouch')) -- true
nLog(string.ends_with('Hello, XXTouch', 'ello', 5)) -- true
```
Note: Uses function outside of this chapter: [`nLog`](/en/docs/handbook/develop-helper/nLog.md)

---

Source: [Left pad string (string.lpad)](https://xxtouch.app/en/docs/handbook/ext-string/string.lpad.md)
Path: handbook/ext-string/string.lpad.md

# Left pad string (string.lpad)

## Declaration

```lua
padded = string.lpad(text, len, pad)
```

## Parameters

- text
  string.
- len
  integer. Target length after padding.
- pad
  string, optional. Padding character(s). Default: space.

## Returns

- padded
  string.

## Description

> Left-pad `text` to length `len` using `pad`.
> Available in versions after 2025-03-13

## Example

```lua
nLog(string.lpad('ff',   6, '0'))  -- 0000ff
nLog(string.lpad('100',  6, '0'))  -- 000100
nLog(string.lpad('1234', 6, '0'))  -- 001234
nLog(string.lpad('123',  6, 'xy')) -- xyx123
```
Note: Uses function outside of this chapter: [`nLog`](/en/docs/handbook/develop-helper/nLog.md)

---

Source: [Right pad string (string.rpad)](https://xxtouch.app/en/docs/handbook/ext-string/string.rpad.md)
Path: handbook/ext-string/string.rpad.md

# Right pad string (string.rpad)

## Declaration

```lua
padded = string.rpad(text, len, pad)
```

## Parameters

- text
  string.
- len
  integer. Target length after padding.
- pad
  string, optional. Padding character(s). Default: space.

## Returns

- padded
  string.

## Description

> Right-pad `text` to length `len` using `pad`.
> Available in versions after 2025-03-13

## Example

```lua
nLog(string.rpad('ff',   6, '0'))  -- ff0000
nLog(string.rpad('100',  6, '0'))  -- 100000
nLog(string.rpad('1234', 6, '0'))  -- 123400
nLog(string.rpad('123',  6, 'xy')) -- 123xyx
```
Note: Uses function outside of this chapter: [`nLog`](/en/docs/handbook/develop-helper/nLog.md)

---

Source: [Extended string samples](https://xxtouch.app/en/docs/handbook/ext-string/samples.md)
Path: handbook/ext-string/samples.md

# Extended string samples

```lua
-- Hash checks
local str = "sozereal"
sys.alert('"'..str..'" in hex is: <'..str:to_hex()..'>')
sys.alert('<'..str:to_hex()..'> back to text: "'..str:to_hex():from_hex()..'"')
sys.alert('MD5("'..str..'") = '..str:md5())
sys.alert('SHA1("'..str..'") = '..str:sha1())
local binstr = "\0\1\2\3\4\5"
sys.alert('<'..binstr:to_hex()..'> MD5 = '..binstr:md5())
sys.alert('<'..binstr:to_hex()..'> SHA1 = '..binstr:sha1())
--
-- Encrypt/Decrypt
local msg = "\5\4\3\2\1\0"
local key = "sozereal"
local emsg = msg:aes128_encrypt(key)
local emsgb64 = emsg:base64_encode()
sys.alert('Binary <'..msg:to_hex()..'>\n AES128 with key "'..key..'" -> <'..emsg:to_hex()..'>\n base64: "'..emsgb64..'"')
local tmp = emsgb64:base64_decode()
msg = tmp:aes128_decrypt(key)
sys.alert('"'..emsgb64..'" base64-decoded <'..tmp:to_hex()..'>\n AES128 with key "'..key..'" decrypted -> <'..msg:to_hex()..'>')
--
-- String helpers
str = "  ha ha,he he,1,3,6  "
new = str:split(",") -- split by ','
sys.alert(new[2])
sys.alert(str:rtrim()) -- "  ha ha,he he,1,3,6"  remove trailing spaces
sys.alert(str:ltrim()) -- "ha ha,he he,1,3,6  "  remove leading spaces
sys.alert(str:trim())  -- "ha ha,he he,1,3,6"    trim both sides
sys.alert(str:atrim()) -- "haha,hehe,1,3,6"     remove all whitespaces
```
Note: This snippet uses function outside of this chapter: [`sys.alert`](/en/docs/handbook/sys/sys.alert.md)

---

Source: [OpenAPI Index](https://xxtouch.app/en/docs/OpenAPI/index.md)
Path: OpenAPI/README.md

# OpenAPI Index

- [Before You Start](START.md)
- [Examples](Demo/README.md)
- [File System](FileSystem/README.md)
    - [List files](FileSystem/file_list.md)
    - [Select a script file](FileSystem/select_script_file.md)
    - [Get the currently selected script file](FileSystem/get_selected_script_file.md)
    - [Run a script file](FileSystem/launch_script_file.md)
    - [Create a directory](FileSystem/mkdir.md)
    - [Remove a directory](FileSystem/rmdir.md)
    - [Rename a file or directory (RAW)](FileSystem/rename_file.md)
    - [Delete a file or empty directory (RAW)](FileSystem/remove_file.md)
    - [Read a file (RAW)](FileSystem/read_file.md)
    - [Write a file (RAW)](FileSystem/write_file.md)
    - [Download a file by redirect](FileSystem/download_file.md)
- [Status](Status/README.md)
    - [Check plaintext script syntax](Status/check_syntax.md)
    - [Get script running status](Status/is_running.md)
    - [Get foreground app orientation](Status/device_front_orien.md)
- [Configuration](Config/README.md)
    - [Get record settings](Config/get_record_conf.md)
    - [Toggle record settings](Config/set_record_conf.md)
    - [Get volume button action settings](Config/get_volume_action_conf.md)
    - [Set volume button actions](Config/set_volume_action_conf.md)
    - [Get startup settings](Config/get_startup_conf.md)
    - [Toggle startup settings](Config/set_startup_conf.md)
    - [Select startup script](Config/select_startup_script_file.md)
    - [Get user preferences](Config/get_user_conf.md)
    - [Set user preferences](Config/set_user_conf.md)
    - [Disable "No SIM" alert](Config/set_no_nosim_alert.md)
    - [Disable "Low Battery" alert](Config/set_no_low_power_alert.md)
    - [Disable "Use Push Notifications to Connect to iTunes" alert](Config/set_no_need_pushid_alert.md)
    - [Set device name](Config/set_device_name.md)
    - [Set screen brightness](Config/set_brightness.md)
    - [Set system volume](Config/set_volume.md)
- [System](System/README.md)
    - [Get installed app info](System/applist.md)
    - [Get device info](System/deviceinfo.md)
    - [Lock screen](System/lock_screen.md)
    - [Unlock screen](System/unlock_screen.md)
    - [Restart service](System/restart.md)
    - [Respring](System/respring.md)
    - [Reboot](System/reboot2.md)
    - [Shutdown](System/halt.md)
    - [Refresh UI cache](System/uicache.md)
    - [Erase all content and settings](System/clear_all.md)
    - [Clear app data](System/clear_app_data.md)
    - [Import an image to Photos](System/image_to_album.md)
    - [Self-update](System/update_deb.md)
    - [Enable remote access](System/open_remote_access.md)
    - [Disable remote access](System/close_remote_access.md)
    - [Check remote access status](System/is_remote_access_opened.md)
- [Script Encryption](Encrypt/README.md)
    - [Encrypt a script file on the device](Encrypt/encript_file.md)
    - [Encrypt a plaintext script](Encrypt/encript.md)
    - [Encrypt a plaintext script and return a download URI](Encrypt/encript_2.md)
- [License](License/README.md)
    - [Bind a license code](License/bind_code.md)
    - [Get the current device's license info](License/device_auth_info.md)
- [Control](Control/README.md)
    - [UDP scan devices on the local network](Control/udp_scan.md)
    - [Launch a script remotely](Control/spawn.md)
    - [Stop script](Control/stop_script.md)
    - [Pause script](Control/pause_script.md)
    - [Resume script](Control/resume_script.md)
    - [Take a remote screenshot](Control/snapshot.md)
    - [Set a process dictionary entry](Control/proc_put.md)
    - [Get a process dictionary entry](Control/proc_get.md)
    - [Push an item into a process dictionary queue](Control/proc_queue_push.md)
    - [Pop an item from a process dictionary queue](Control/proc_queue_pop.md)
    - [Clear all items from a process dictionary queue](Control/proc_queue_clear.md)

---

Source: [Examples](https://xxtouch.app/en/docs/OpenAPI/Demo/index.md)
Path: OpenAPI/Demo/README.md

# Examples

- [Simple XXT LAN Controller example [aardio version] - 0.0.0.57.zip - 12.3kB](/zip/XXT%E5%B1%80%E5%9F%9F%E7%BD%91%E6%8E%A7%E5%88%B6%E5%99%A8%E7%AE%80%E6%98%93%E7%A4%BA%E4%BE%8B%5Baardio%E7%89%88%5D-0.0.0.57.zip)
- Note: [aardio](https://www.aardio.com/) is a rapid development tool for Windows

---

Source: [File System](https://xxtouch.app/en/docs/OpenAPI/FileSystem/index.md)
Path: OpenAPI/FileSystem/README.md

# File System

- [List files](file_list.md)
- [Select a script file](select_script_file.md)
- [Get the currently selected script file](get_selected_script_file.md)
- [Run a script file](launch_script_file.md)
- [Check encrypted script](api-check_xxt.md)
- [Create a directory](mkdir.md)
- [Remove a directory](rmdir.md)
- [Rename a file or directory (RAW)](rename_file.md)
- [Delete a file or empty directory (RAW)](remove_file.md)
- [Read a file (RAW)](read_file.md)
- [Write a file (RAW)](write_file.md)
- [Download a file by redirect](download_file.md)

---

Source: [Status](https://xxtouch.app/en/docs/OpenAPI/Status/index.md)
Path: OpenAPI/Status/README.md

# Status

- [Check plaintext script syntax](check_syntax.md)
- [Get script running status](is_running.md)
- [Get foreground app orientation](device_front_orien.md)

---

Source: [Configuration](https://xxtouch.app/en/docs/OpenAPI/Config/index.md)
Path: OpenAPI/Config/README.md

# Configuration

- [Get record settings](get_record_conf.md)
- [Toggle record settings](set_record_conf.md)
- [Get volume button action settings](get_volume_action_conf.md)
- [Set volume button actions](set_volume_action_conf.md)
- [Get startup settings](get_startup_conf.md)
- [Toggle startup settings](set_startup_conf.md)
- [Select startup script](select_startup_script_file.md)
- [Get user preferences](get_user_conf.md)
- [Set user preferences](set_user_conf.md)
- [Disable "No SIM" alert](set_no_nosim_alert.md)
- [Disable "Low Battery" alert](set_no_low_power_alert.md)
- [Disable "Use Push Notifications to Connect to iTunes" alert](set_no_need_pushid_alert.md)
- [Set device name](set_device_name.md)
- [Set screen brightness](set_brightness.md)
- [Set system volume](set_volume.md)

---

Source: [System](https://xxtouch.app/en/docs/OpenAPI/System/index.md)
Path: OpenAPI/System/README.md

# System

- [Get installed app info](applist.md)
- [Get device info](deviceinfo.md)
- [Lock screen](lock_screen.md)
- [Unlock screen](unlock_screen.md)
- [Restart service](restart.md)
- [Respring](respring.md)
- [Reboot](reboot2.md)
- [Shutdown](halt.md)
- [Clear UI cache](uicache.md)
- [Erase all content and settings](clear_all.md)
- [Clear app data](clear_app_data.md)
- [Import an image to Photos](image_to_album.md)
- [Self-update](update_deb.md)
- [Enable remote access](open_remote_access.md)
- [Disable remote access](close_remote_access.md)
- [Check remote access status](is_remote_access_opened.md)

---

Source: [Script Encryption](https://xxtouch.app/en/docs/OpenAPI/Encrypt/index.md)
Path: OpenAPI/Encrypt/README.md

# Script Encryption

- [Encrypt a script file on the device](encript_file.md)
- [Encrypt a plaintext script](encript.md)
- [Encrypt a plaintext script and return a download URI](encript_2.md)

---

Source: [License](https://xxtouch.app/en/docs/OpenAPI/License/index.md)
Path: OpenAPI/License/README.md

# License

- [Bind a license code](bind_code.md)
- [Get the current device's license info](device_auth_info.md)

---

Source: [Control](https://xxtouch.app/en/docs/OpenAPI/Control/index.md)
Path: OpenAPI/Control/README.md

# Control

- [UDP scan devices on the local network](udp_scan.md)
- [Launch a script remotely](spawn.md)
- [Stop script](stop_script.md)
- [Pause script](pause_script.md)
- [Resume script](resume_script.md)
- [Take a remote screenshot](snapshot.md)
- [Set a process dictionary entry](proc_put.md)
- [Get a process dictionary entry](proc_get.md)
- [Push an item into a process dictionary queue](proc_queue_push.md)
- [Pop an item from a process dictionary queue](proc_queue_pop.md)
- [Clear all items from a process dictionary queue](proc_queue_clear.md)

---

Source: [Get Recording Settings](https://xxtouch.app/en/docs/OpenAPI/Config/get_record_conf.md)
Path: OpenAPI/Config/get_record_conf.md

# Get Recording Settings

- Description

    ```http
    POST /get_record_conf HTTP/1.1
    ```

- Possible Responses

    ```json
    {
        "code":0,
        "message":"操作成功",
        "data":{
            "record_volume_up":true,  // Whether recordings include Volume Up
            "record_volume_down":true // Whether recordings include Volume Down
        }
    }
    ```

---

Source: [UDP Scan Devices on the Local Network](https://xxtouch.app/en/docs/OpenAPI/Control/udp_scan.md)
Path: OpenAPI/Control/udp_scan.md

# UDP Scan Devices on the Local Network

- First, open a UDP receiving port on the computer.

- Then send the following UDP broadcast to port 46953 on the local network:

    ```json
    {"ip":"computer IP address","port":50000} // port is the computer's listening port
    ```

- The device will reply to the computer's receiving port with:

    ```json
    {
        "ip":"192.168.31.99",
        "port":"46952",
        "devname":"Device Name",
        "deviceid":"123456789012345678901234567890123456790", // device UDID
        "devsn":"XXXXXXXXXXXX",                               // device serial number
        "devmac":"02:03:04:05:06:07",                         // device Wi‑Fi MAC address
        "devtype":"iPhone8,1",                                // device model
        "zeversion":"0.0.1.738",                              // service version
        "sysversion":"9.0.2"                                  // iOS version
    }
    ```

- Computer-side UDP scan example (Python 3.x):

    ```python
    # -*- coding: utf-8 -*-
    import socket
    import json

    local_ip = '192.168.31.13'  # computer IP address
    local_port = 31500

    local = (local_ip, local_port)
    remote = ("255.255.255.255", 46953)
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.bind(local)

    s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
    s.sendto(json.dumps({"ip": local_ip, "port": local_port}).encode('utf-8'), remote)  # encode as UTF-8

    while True:
        data, addr = s.recvfrom(2048)
        if not data:
            print("client has exited")
            break
        print("received:", data, "from", addr)

    s.close()
    ```

- Computer-side UDP scan example (Node.js):

    ```javascript
    const http = require('http');
    const dgram = require('dgram');

    const server_Port = 31500;  // UDP receive port
    const client_Port = 31501;  // UDP send port

    const device_List = {};     // device list

    // UDP server (receive)
    const server_Socket = dgram.createSocket('udp4');
    server_Socket.on('message', function(msg, rinfo){
        console.log('received: %s', msg);
        const device_Info = JSON.parse(msg);
        if (device_Info.deviceid) {
            device_List[device_Info.deviceid] = device_Info; // de-duplicate by deviceid
        }
    });
    server_Socket.bind(server_Port);

    // UDP client (send)
    const client_Socket = dgram.createSocket('udp4');
    client_Socket.bind(client_Port);

    function search(){
        const server_List = [];
        const os = require('os');
        const ifaces = os.networkInterfaces();
        for (const dev in ifaces) {
            ifaces[dev].forEach(function(details){
                if (details.family === 'IPv4') {
                    server_List.push(details.address);
                }
            });
        }
        for (const address of server_List) {
            const ip_ar = address.split(".");
            const send2ip = `${ip_ar[0]}.${ip_ar[1]}.${ip_ar[2]}.255`;
            const client_Socket = dgram.createSocket('udp4');
            const msg = JSON.stringify({ip: address, port: server_Port});
            client_Socket.send(msg, 0, msg.length, 46953, send2ip);
        }
    }

    http.createServer(function (request, response) {
        response.writeHead(200, {'Content-Type': 'application/json'});
        search();
        response.end(JSON.stringify(device_List));
    }).listen(22222);

    search();
    console.log('Web service at: http://127.0.0.1:22222/');
    ```

---

Source: [Encrypt a Script File on the Device](https://xxtouch.app/en/docs/OpenAPI/Encrypt/encript_file.md)
Path: OpenAPI/Encrypt/encript_file.md

# Encrypt a Script File on the Device

- Description

    ```http
    POST /encript_file HTTP/1.1

    {
        "no_strip": true|false,             // keep debug info; default false
        "in_file": "lua/scripts/xxx.lua",   // input file; can be absolute path
        "out_file": "lua/scripts/xxx.xxt",   // output file; can be absolute path
        "info": {},                         // metadata to embed in script
        "entitlements": {
            "allow-external-require": true|false
        }
    }
    ```

- Parameters

    - `no_strip`: `boolean`
        When true, keep debug info so stack traces retain line numbers. Default false
    - `in_file`: `string`
        Path to the script file to encrypt; accepts absolute paths or ones relative to `/var/mobile/Media/1ferver/`
    - `out_file`: `string`
        Target path for the encrypted script; accepts absolute paths or ones relative to `/var/mobile/Media/1ferver/`
    - `info`: `table`
        Additional metadata to embed in the script (e.g., `Name`, `Version`, `Description`)
    - `entitlements`: `table`
        Script permission configuration
        - `allow-external-require`
            If missing or false, only scripts encrypted with the same author certificate may `require` this script. If a list, scripts signed by the listed certificate authors are allowed. If true, any script may `require` it.

- Possible Responses

    ```json
    {"code":0,"message":"操作成功"}
    ```
    ```json
    {"code":2,"message":"脚本有语法错误","detail":"specific error details"}
    ```
    ```json
    {"code":4,"message":"文件或目录不存在"} // input file cannot be read
    ```
    ```json
    {"code":4,"message":"无法写入文件"}
    ```
    ```json
    {"code":8,"message":"参数错误"}
    ```
    ```json
    {"code":13,"message":"另外一项加密正在进行..."}
    ```

- Notes
    - Root directory for file operations: `/var/mobile/Media/1ferver/`

---

Source: [List Files](https://xxtouch.app/en/docs/OpenAPI/FileSystem/file_list.md)
Path: OpenAPI/FileSystem/file_list.md

# List Files

- Description

    ```http
    POST /file_list HTTP/1.1

    {"directory":"/lua/scripts/"}
    ```

- Possible Responses

    ```json
    {
        "code": 0,
        "message": "操作成功",
        "data": {
            "list": [
                {
                    "name": "file name",
                    "change": 1446566100,
                    "size": 144,
                    "access": 1442128726,
                    "gid": 20,
                    "blksize": 4096,
                    "uid": 0,
                    "rdev": 0,
                    "blocks": 8,
                    "nlink": 1,
                    "permissions": "rw-r--r--",
                    "mode": "file",
                    "dev": 16777219,
                    "ino": 4887321,
                    "modification": 1443063784
                },
                {
                    "name": "directory name",
                    "change": 1464135126,
                    "size": 102,
                    "access": 1464135114,
                    "gid": 20,
                    "blksize": 4096,
                    "uid": 0,
                    "rdev": 0,
                    "blocks": 0,
                    "nlink": 2,
                    "permissions": "rwxr-xr-x",
                    "mode": "directory",
                    "dev": 16777219,
                    "ino": 9407305,
                    "modification": 1464135126
                }
            ]
        }
    }
    ```

- Python 3.x example to fetch the script list (requires `requests`):

    ```python
    # -*- coding: utf-8 -*-
    import requests

    resp = requests.post(
        "http://192.168.31.72:46952/file_list",
        json={"directory": "/lua/scripts/"},
        timeout=30,
    )

    if resp.status_code == 200:
        ret = resp.json()
        if ret.get("code") == 0:
            for finfo in ret["data"]["list"]:
                name = finfo.get("name")
                if name not in (".", ".."):
                    print(name)
        else:
            print(ret.get("message"))
    else:
        print(resp.status_code, resp.reason)
        print(resp.text)
    ```

- Notes
    - The root directory for file operations via this API is `/var/mobile/Media/1ferver/`
    - Open-source script modules directory: `/var/mobile/Media/1ferver/lua/`
    - Scripts directory: `/var/mobile/Media/1ferver/lua/scripts/`
    - Plugins directory: `/var/mobile/Media/1ferver/lib/`
    - Resources directory: `/var/mobile/Media/1ferver/res/`
    - Logs directory: `/var/mobile/Media/1ferver/log/`
    - UI config directory: `/var/mobile/Media/1ferver/uicfg/`
    - OCR language data directory: `/var/mobile/Media/1ferver/tessdata/`

---

Source: [Bind a License Code](https://xxtouch.app/en/docs/OpenAPI/License/bind_code.md)
Path: OpenAPI/License/bind_code.md

# Bind a License Code

- Description

    ```http
    POST /bind_code HTTP/1.1

    XXXXXXXXXXXXXXXX
    ```

- Possible Responses

    ```json
    {"code":0,"message":"充值成功，新增授权时间 XX 天 XX 小时 XX 分钟"} // binding succeeded
    ```
    ```json
    {"code":1,"message":"操作失败"} // failed to connect to server
    ```
    ```json
    {"code":-1,"message":"..."} // other non-zero codes describe the reason in message
    ```

---

Source: [Before You Start](https://xxtouch.app/en/docs/OpenAPI/START.md)
Path: OpenAPI/START.md

# Before You Start

XXTouch OpenAPI is the HTTP interface exposed by the XXTouch daemon running on the device. It listens for incoming requests and executes commands, enabling developers to remotely control XXTouch — ideal for centralized management, remote debugging, and file transfer.

## Prerequisites

- **Enable Remote Service**
  If you are developing from a desktop, enable the remote service on the device first.
  Steps: `Open App → More → Remote Service → Enable`
  See the illustrated guide: [User Manual](/en/docs/ABC/index.md#how-to-enable-remote-interface)

## Protocol Conventions

| Item | Value |
| --- | --- |
| Protocol | `HTTP/1.1` |
| Default port | `46952` |
| Text encoding | `UTF-8` (both request and response) |
| Success status code | `200` |
| Remote service disabled | All endpoints return `400` |

---

Source: [Syntax Check for Plaintext Script Content](https://xxtouch.app/en/docs/OpenAPI/Status/check_syntax.md)
Path: OpenAPI/Status/check_syntax.md

# Syntax Check for Plaintext Script Content

- Description

    ```http
    POST /check_syntax HTTP/1.1

    Plaintext script content
    ```

- Possible Responses

    ```json
    {"code":0,"message":"语法检测已通过"}
    ```
    ```json
    {"code":2,"message":"脚本有语法错误","detail":"specific error details"}
    ```

---

Source: [Get Installed App Info](https://xxtouch.app/en/docs/OpenAPI/System/applist.md)
Path: OpenAPI/System/applist.md

# Get Installed App Info

- Description

    ```http
    POST /applist HTTP/1.1

    {"no_icon": true|false}
    ```

- Possible Responses

    ```json
    {
        "code":0,
        "message":"操作成功",
        "data":[
            {
                "bid":"com.xxx.xxx.1",
                "name":"Localized app name",
                "bundle_path":"App bundle path",
                "data_path":"App data path",
                "icon":"App icon data (base64)"
            },
            {
                "bid":"com.xxx.xxx.2",
                "name":"Localized app name",
                "bundle_path":"App bundle path",
                "data_path":"App data path",
                "icon":"App icon data (base64)"
            }
        ]
    }
    ```
    ```json
    {"code":8,"message":"参数错误"}
    ```

- Notes
    - `no_icon` is optional. When `true`, returns all fields except the `icon` data

---

Source: [Recording Settings Switches](https://xxtouch.app/en/docs/OpenAPI/Config/set_record_conf.md)
Path: OpenAPI/Config/set_record_conf.md

# Recording Settings Switches

- Description

    Include Volume Up in recordings
    ```http
    POST /set_record_volume_up_on HTTP/1.1
    ```
    Exclude Volume Up from recordings
    ```http
    POST /set_record_volume_up_off HTTP/1.1
    ```
    Include Volume Down in recordings
    ```http
    POST /set_record_volume_down_on HTTP/1.1
    ```
    Exclude Volume Down from recordings
    ```http
    POST /set_record_volume_down_off HTTP/1.1
    ```

- Possible Responses

    ```json
    {"code":0,"message":"操作成功"}
    ```

---

Source: [Remote Script Launch API](https://xxtouch.app/en/docs/OpenAPI/Control/spawn.md)
Path: OpenAPI/Control/spawn.md

# Remote Script Launch API

- Description

    ```http
    POST /spawn HTTP/1.1
    spawn_args: {"script launch args": ...}

    [script body]
    ```

- Possible Responses

    ```json
    {"code":1,"message":"操作失败"}
    ```
    ```json
    {"code":2,"message":"脚本有语法错误","detail":"specific error details"}
    ```
    ```json
    {"code":3,"message":"已经有脚本正在运行中"}
    ```
    ```json
    {"code":233,"message":"未知错误"}
    ```

- Notes
    - `spawn_args` is a printable string without line breaks
    - `[script body]` can be plain text or encrypted binary data
    - The script can read launch args via `proc_get("spawn_args")` or `proc_take("spawn_args")`
    - The script will not be saved to the device as a file; it only runs in memory
    - Exception: when script daemon mode is enabled, the device may cache script data bound to that device

- Example

    Example HTTP request to the device:
    ```http
    POST /spawn HTTP/1.1
    spawn_args: {"server_ip":"192.168.31.13","port":55555}
    Content-Length: 123

    local args = proc_get("spawn_args")
    args = json.decode(args)
    sys.alert("Server IP: "..args.server_ip.."\nPort: "..args.port)
    ```

    The device will show an alert:
    ```
    Server IP: 192.168.31.13
    Port: 55555
    ```

    Python 3.x example:

    ```python
    # -*- coding: utf-8 -*-

    import http.client
    import json

    spawn_args = {
        "server_ip": "192.168.31.13",
        "port": 55555,
    }

    data = r'''
    local args = proc_get("spawn_args")
    args = json.decode(args)
    sys.alert("Server IP: "..args.server_ip.."\nPort: "..args.port)
    '''

    headers = {
        "Content-type": "text/lua",
        "spawn_args": json.dumps(spawn_args),
    }

    conn = http.client.HTTPConnection("192.168.31.72:46952")
    conn.request("POST", "/spawn", data.encode('utf-8'), headers)

    response = conn.getresponse()
    print(response.status, response.reason)

    data = response.read()
    print(data.decode('utf-8'))

    conn.close()
    ```

---

Source: [Encrypt a Plaintext Script](https://xxtouch.app/en/docs/OpenAPI/Encrypt/encript.md)
Path: OpenAPI/Encrypt/encript.md

# Encrypt a Plaintext Script

- Description

    ```http
    POST /encript HTTP/1.1
    args: {"no_strip":true|false, "info":{}, "entitlements":{}, "xuic":true|false}

    [script content]
    ```

- Parameters

    - `no_strip`: `boolean`
        When true, keep debug info so stack traces retain line numbers. Default false
    - `info`: `table`
        Metadata bundled with the script, such as `Name`, `Version`, `Description`, etc.
    - `entitlements`: `table`
        Script permission configuration
        - `allow-external-require`
            If missing or false, only scripts encrypted with the same author certificate may `require` this script. If a list, scripts signed by the listed authors are allowed. If true, any script may `require` it.
    - `xuic`: `boolean`
        When true, encrypt an XUI file into XUIC format and ignore other parameters. Default false
    - `script content`: `string`
        The plaintext script body to encrypt, sent as the request payload

- Possible Responses

    - Success: status code `200` with body
        ```
        [encrypted script content]
        ```
    - Failure: status code `400` with body
        ```json
        {"code":2,"message":"脚本有语法错误","detail":"specific error details"}
        ```
        ```json
        {"code":13,"message":"另外一项加密正在进行..."}
        ```

---

Source: [Select a Script File](https://xxtouch.app/en/docs/OpenAPI/FileSystem/select_script_file.md)
Path: OpenAPI/FileSystem/select_script_file.md

# Select a Script File

- Description

    ```http
    POST /select_script_file HTTP/1.1

    {"filename":"file name"}
    ```

- Possible Responses

    ```json
    {"code":0,"message":"操作成功"}
    ```
    ```json
    {"code":1,"message":"操作失败"}
    ```
    ```json
    {"code":4,"message":"无法读取文件"}
    ```
    ```json
    {"code":8,"message":"参数错误"}
    ```

- Python 3.x example (requires `requests`):

    ```python
    # -*- coding: utf-8 -*-
    import requests

    resp = requests.post(
        "http://192.168.31.72:46952/select_script_file",
        json={"filename": "123.lua"},
        timeout=30,
    )

    print(resp.status_code, resp.reason)  # 200 OK on success
    print(resp.json().get("message") if resp.status_code == 200 else resp.text)
    ```

- Notes
    - The root directory for this API is `/var/mobile/Media/1ferver/lua/scripts/`

---

Source: [Get Current Device License Info](https://xxtouch.app/en/docs/OpenAPI/License/device_auth_info.md)
Path: OpenAPI/License/device_auth_info.md

# Get Current Device License Info

- Description

    ```http
    POST /device_auth_info HTTP/1.1
    ```

- Possible Responses

    ```json
    {
        "code":0,
        "message":"ok",
        "data":{
            "nowDate": 1517149407,
            "expireDate": 1517149407 // expired if expireDate - nowDate <= 0
        }
    }
    ```
    ```json
    {"code":1,"message":"操作失败"} // failed to connect to server
    ```
    ```json
    {"code":-1,"message":"..."} // other non-zero codes describe the reason in message
    ```

---

Source: [Get Script Running Status](https://xxtouch.app/en/docs/OpenAPI/Status/is_running.md)
Path: OpenAPI/Status/is_running.md

# Get Script Running Status

- Description

    ```http
    POST /is_running HTTP/1.1
    ```

- Possible Responses

    ```json
    {"code":0,"message":"操作成功"} // no script is running and no recording is in progress
    ```
    ```json
    {"code":3,"message":"已经有脚本正在运行中"}
    ```
    ```json
    {"code":9,"message":"当前正在录制"}
    ```

---

Source: [Get Device Info](https://xxtouch.app/en/docs/OpenAPI/System/deviceinfo.md)
Path: OpenAPI/System/deviceinfo.md

# Get Device Info

- Description

    ```http
    POST /deviceinfo HTTP/1.1
    ```

- Possible Responses

    ```json
    {
        "code":0,
        "message":"操作成功",
        "data":{
            "devsn":"XXXXXXXXXXXX",                                // Device serial number
            "zeversion":"0.0.1.733",                               // Service version
            "sysversion":"7.1.2",                                  // System version
            "devname":"Device Name",                               // Device name
            "devmac":"10:11:12:13:14:15",                          // Device MAC address
            "deviceid":"1234567890123456789012345678901234567890", // Device UDID
            "devtype":"iPhone5,3",                                 // Device model
            "wifi_ip":"192.168.1.100",                             // Wi-Fi IP address
            "ipaddr":"127.0.0.1",                                  // Local address used for the current request
            "port":46952                                           // Port
        }
    }
    ```

---

Source: [Get Volume Button Action Settings](https://xxtouch.app/en/docs/OpenAPI/Config/get_volume_action_conf.md)
Path: OpenAPI/Config/get_volume_action_conf.md

# Get Volume Button Action Settings

- Description

    ```http
    POST /get_volume_action_conf HTTP/1.1
    ```

- Possible Responses

    ```json
    {
        "code":0,
        "message":"操作成功",
        "data":{
            "hold_volume_up":"0",   // 0: Start/Stop Script (with prompt), 1: Start/Stop Script, 2: No Action; same below
            "hold_volume_down":"0",
            "click_volume_up":"0",
            "click_volume_down":"0",
            "activator_installed":true // If Activator is installed, these settings do not take effect
        }
    }
    ```

---

Source: [Stop Script API](https://xxtouch.app/en/docs/OpenAPI/Control/stop_script.md)
Path: OpenAPI/Control/stop_script.md

# Stop Script API

- Description

    ```http
    POST /stop_script HTTP/1.1
    ```

- Possible Responses

    ```json
    {"code":0,"message":"脚本即将停止"}
    ```

- Notes
    - This response does not guarantee the script has fully stopped. You can check via `/is_running`.

---

Source: [Encrypt a Plaintext Script and Return a Download URI](https://xxtouch.app/en/docs/OpenAPI/Encrypt/encript_2.md)
Path: OpenAPI/Encrypt/encript_2.md

# Encrypt a Plaintext Script and Return a Download URI

- Description

    ```http
    POST /encript HTTP/1.1
    args: {"no_strip":true|false, "info":{}, "entitlements":{}, "xuic":true|false, "filename":"UTF-8 URI-encoded filename"}

    [script content]
    ```

- Parameters

    - `no_strip`: `boolean`
        When true, keep debug info so stack traces retain line numbers. Default false
    - `info`: `table`
        Metadata bundled with the script, such as `Name`, `Version`, `Description`, etc.
    - `entitlements`: `table`
        Script permission configuration
        - `allow-external-require`
            If missing or false, only scripts encrypted with the same author certificate may `require` this script. If a list, scripts signed by the listed authors are allowed. If true, any script may `require` it.
    - `xuic`: `boolean`
        When true, encrypt an XUI file into XUIC format and ignore other parameters. Default false
    - `filename`: `string`
        Filename to use when downloading via the returned URI; must be UTF-8 URI encoded in advance
    - `script content`: `string`
        The plaintext script body to encrypt, sent as the request payload

- Possible Responses

    - Success: status code `200` with body
        ```json
        {
            "code":0,
            "message":"操作成功",
            "download_uri":"/download_encript" // download the encrypted file via this URI
        }
        ```
    - Failure: status code `400` with body
        ```json
        {"code":2,"message":"操作失败"}
        ```
        ```json
        {"code":2,"message":"脚本有语法错误","detail":"specific error details"}
        ```
        ```json
        {"code":13,"message":"另外一项加密正在进行..."}
        ```

---

Source: [Get Currently Selected Script File](https://xxtouch.app/en/docs/OpenAPI/FileSystem/get_selected_script_file.md)
Path: OpenAPI/FileSystem/get_selected_script_file.md

# Get Currently Selected Script File

- Description

    ```http
    POST /get_selected_script_file HTTP/1.1
    ```

- Possible Responses

    ```json
    {
        "code": 0,
        "message": "操作成功",
        "data": {
            "filename": "currently selected filename"
        }
    }
    ```

- Python 3.x example (requires `requests`):

    ```python
    # -*- coding: utf-8 -*-
    import requests

    resp = requests.post("http://192.168.31.72:46952/get_selected_script_file", timeout=30)

    if resp.status_code == 200:
        ret = resp.json()
        print(ret.get("message"))
        if ret.get("code") == 0:
            print(ret["data"]["filename"])
    else:
        print(resp.status_code, resp.reason)
        print(resp.text)
    ```

- Notes
    - The root directory for this API is `/var/mobile/Media/1ferver/lua/scripts/`

---

Source: [Get Foreground App Orientation](https://xxtouch.app/en/docs/OpenAPI/Status/device_front_orien.md)
Path: OpenAPI/Status/device_front_orien.md

# Get Foreground App Orientation

- Description

    ```http
    POST /device_front_orien HTTP/1.1
    ```

- Possible Responses

    ```json
    {"code":0,"message":"操作成功","data":{"orien":0}} // 0: Home at bottom; 1: Home at right; 2: Home at left; 3: Home at top; 4: unknown
    ```

---

Source: [Lock Screen](https://xxtouch.app/en/docs/OpenAPI/System/lock_screen.md)
Path: OpenAPI/System/lock_screen.md

# Lock Screen

- Description

    ```http
    POST /lock_screen HTTP/1.1
    ```

- Possible Responses

    ```json
    {"code":0,"message":"操作成功"}
    ```

---

Source: [Set Volume Button Actions](https://xxtouch.app/en/docs/OpenAPI/Config/set_volume_action_conf.md)
Path: OpenAPI/Config/set_volume_action_conf.md

# Set Volume Button Actions

- Description

    Set the action for holding Volume Up
    ```http
    POST /set_hold_volume_up_action HTTP/1.1

    0|1|2
    ```
    Set the action for holding Volume Down
    ```http
    POST /set_hold_volume_down_action HTTP/1.1

    0|1|2
    ```
    Set the action for pressing Volume Up once
    ```http
    POST /set_click_volume_up_action HTTP/1.1

    0|1|2
    ```
    Set the action for pressing Volume Down once
    ```http
    POST /set_click_volume_down_action HTTP/1.1

    0|1|2
    ```

- Possible Responses

    ```json
    {"code":0,"message":"操作成功"}
    ```

---

Source: [Pause Script API](https://xxtouch.app/en/docs/OpenAPI/Control/pause_script.md)
Path: OpenAPI/Control/pause_script.md

# Pause Script API

- Description

    ```http
    POST /pause_script HTTP/1.1
    ```

- Possible Responses

    ```json
    {"code":0,"message":"操作成功"}
    ```

- Notes
    - This interrupts the script at any point where it can yield or wait. This API is strongly discouraged for general use.
    - Repeated calls have no extra effect.
    - This API is triggered when the volume-key selection menu appears; avoid conflicts if you rely on that feature.

---

Source: [Run a Script File](https://xxtouch.app/en/docs/OpenAPI/FileSystem/launch_script_file.md)
Path: OpenAPI/FileSystem/launch_script_file.md

# Run a Script File

- Description

    ```http
    POST /launch_script_file HTTP/1.1

    {"filename": "script file name"}
    ```

- Notes
    `filename` is optional. If omitted, the currently selected script file will be used.
    It first looks in `/var/mobile/Media/1ferver/lua/scripts/`. If not found there, it treats the path as an absolute path.

- Possible Responses

    ```json
    {"code":0,"message":"脚本运行开始"}
    ```
    ```json
    {"code":1,"message":"操作失败"}
    ```
    ```json
    {"code":2,"message":"脚本有语法错误","detail":"specific error details"}
    ```
    ```json
    {"code":3,"message":"已有脚本正在运行中"}
    ```
    ```json
    {"code":4,"message":"无法读取文件"}
    ```
    ```json
    {"code":8,"message":"参数错误"}
    ```
    ```json
    {"code":9,"message":"脚本已损坏"}
    ```
    ```json
    {"code":10,"message":"软件需要更新方能支持使用这个脚本"}
    ```

- Python 3.x example (run the currently selected script, requires `requests`):

    ```python
    # -*- coding: utf-8 -*-
    import requests

    resp = requests.post("http://192.168.31.72:46952/launch_script_file", timeout=30)

    if resp.status_code == 200:
        print(resp.json().get("message"))
    else:
        print(resp.status_code, resp.reason)
        print(resp.text)
    ```

---

Source: [Unlock Screen](https://xxtouch.app/en/docs/OpenAPI/System/unlock_screen.md)
Path: OpenAPI/System/unlock_screen.md

# Unlock Screen

- Description

    ```http
    POST /unlock_screen HTTP/1.1
    ```

- Possible Responses

    ```json
    {"code":0,"message":"操作成功"}
    ```

---

Source: [Get Startup Settings](https://xxtouch.app/en/docs/OpenAPI/Config/get_startup_conf.md)
Path: OpenAPI/Config/get_startup_conf.md

# Get Startup Settings

- Description

    ```http
    POST /get_startup_conf HTTP/1.1
    ```

- Possible Responses

    ```json
    {
        "code":0,
        "message":"操作成功",
        "data":{
            "startup_run":true,        // true: launch at startup enabled; false: disabled
            "startup_script":"Script name to launch at startup"
        }
    }
    ```
    ```json
    {"code":5,"message":"配置文件有误"}
    ```

---

Source: [Resume Script API](https://xxtouch.app/en/docs/OpenAPI/Control/resume_script.md)
Path: OpenAPI/Control/resume_script.md

# Resume Script API

- Description

    ```http
    POST /resume_script HTTP/1.1
    ```

- Possible Responses

    ```json
    {"code":0,"message":"操作成功"}
    ```

- Notes
    - After calling the pause API, use this API to resume script execution. This API is strongly discouraged for general use.
    - Repeated calls have no extra effect.
    - This API is triggered when the volume-key selection menu is canceled; avoid conflicts if you rely on that feature.

---

Source: [Check Encrypted Script](https://xxtouch.app/en/docs/OpenAPI/FileSystem/api-check_xxt.md)
Path: OpenAPI/FileSystem/api-check_xxt.md

# Check Encrypted Script

- Description

    ```http
    POST /api/check-xxt HTTP/1.1

    [XXT script]
    ```

- Parameters

    - `XXT script`: `string` | `json`
        Provide either the raw XXT script content to inspect, or a JSON payload like below:

        ```json
        {"filename": "Path to XXT script on the device"}
        ```

- Possible Responses

    ```json
    {"code":0,"message":"操作成功","data":{"info":"...","entitlements":"...","cert_info":{...}}}
    ```
    ```json
    {"code":4,"message":"无法读取文件"}
    ```
    ```json
    {"code":8,"message":"参数错误"}
    ```

- Python 3.x example (requires `requests`):

    ```python
    # -*- coding: utf-8 -*-
    import requests

    resp = requests.post(
        "http://192.168.11.115:46952/api/check-xxt",
        json={"filename": "/var/mobile/Media/1ferver/lua/scripts/1.xxt"},
        timeout=30,
    )

    if resp.status_code == 200:
        print("Success, content:", resp.content)
    else:
        print("Failed:", resp.status_code, resp.content)
    ```

---

Source: [Restart Service](https://xxtouch.app/en/docs/OpenAPI/System/restart.md)
Path: OpenAPI/System/restart.md

# Restart Service

- Description

    ```http
    POST /restart HTTP/1.1
    ```

- Possible Responses

    ```json
    {"code":0,"message":"操作成功"}
    ```

---

Source: [Startup Settings Switch](https://xxtouch.app/en/docs/OpenAPI/Config/set_startup_conf.md)
Path: OpenAPI/Config/set_startup_conf.md

# Startup Settings Switch

- Description

    Enable launch at startup
    ```http
    POST /set_startup_run_on HTTP/1.1
    ```
    Disable launch at startup
    ```http
    POST /set_startup_run_off HTTP/1.1
    ```

- Possible Responses

    ```json
    {"code":0,"message":"操作成功"}
    ```
    ```json
    {"code":1,"message":"脚本运行的过程中无法做出该操作"}
    ```

---

Source: [Remote Screenshot API](https://xxtouch.app/en/docs/OpenAPI/Control/snapshot.md)
Path: OpenAPI/Control/snapshot.md

# Remote Screenshot API

- Description

    ```http
    GET /snapshot?ext=[extension]&compress=[ratio]&orient=[orientation]&zoom=[scale]&left=[left]&top=[top]&right=[right]&bottom=[bottom] HTTP/1.1
    ```

- Possible Responses

    Image data

- Notes
    - `[extension]` can be `png` or `jpg`
    - `[ratio]` ranges from `0~1`; if it is less than `1`, `jpg` format is used automatically
    - `[orientation]` range `0~3`:
        - `0` portrait, home at bottom
        - `1` landscape, home at right
        - `2` landscape, home at left
        - `3` portrait, home at top
    - `[scale]` ranges from `0~3`; default `1`; available since `1.0.7-1`
    - `[left]`, `[top]`, `[right]`, `[bottom]` define a capture region; invalid region means full screen; available since `1.0.7-1`

---

Source: [Respring Device](https://xxtouch.app/en/docs/OpenAPI/System/respring.md)
Path: OpenAPI/System/respring.md

# Respring Device

- Description

    ```http
    POST /respring HTTP/1.1
    ```

- Possible Responses

    ```json
    {"code":0,"message":"操作成功"}
    ```

---

Source: [Select Startup Script](https://xxtouch.app/en/docs/OpenAPI/Config/select_startup_script_file.md)
Path: OpenAPI/Config/select_startup_script_file.md

# Select Startup Script

- Description

    ```http
    POST /select_startup_script_file HTTP/1.1

    {"filename":"file name"}
    ```

- Possible Responses

    ```json
    {"code":0,"message":"操作成功"}
    ```
    ```json
    {"code":1,"message":"脚本运行的过程中无法做出该操作"}
    ```

---

Source: [Set Value of a Process Dictionary Entry](https://xxtouch.app/en/docs/OpenAPI/Control/proc_put.md)
Path: OpenAPI/Control/proc_put.md

# Set Value of a Process Dictionary Entry

- Description

    ```http
    POST /proc_put HTTP/1.1

    {"key":"[key]","value":"[value]"}
    ```

- Possible Responses

    ```json
    {"code":0,"message":"操作成功","key":"[key]","old_value":"[old value]","value":"[new value]"}
    ```
    ```json
    {"code":1,"message":"操作失败"}
    ```

- Notes
    - Store an entry with key `[key]` and value `[value]` in the running XXTouch service process dictionary on the device
    - `[key]` is used to retrieve the value
    - `[value]` is a string

- Example

    For example, send this request to the device:
    ```http
    POST /proc_put HTTP/1.1
    Content-Length: 45

    {"key":"greeting","value":"Hello World"}
    ```

    If the device script contains:
    ```lua
    sys.alert(proc_get("greeting"))
    ```

    The device displays an alert:
    ```
    Hello World
    ```

---

Source: [Reboot Device](https://xxtouch.app/en/docs/OpenAPI/System/reboot2.md)
Path: OpenAPI/System/reboot2.md

# Reboot Device

- Description

    ```http
    POST /reboot2 HTTP/1.1
    ```

- Possible Responses

    ```json
    {"code":0,"message":"操作成功"}
    ```

---

Source: [Get User Preferences](https://xxtouch.app/en/docs/OpenAPI/Config/get_user_conf.md)
Path: OpenAPI/Config/get_user_conf.md

# Get User Preferences

- Description

    ```http
    POST /get_user_conf HTTP/1.1
    ```

- Possible Responses

    ```json
    {
        "code":0,
        "message":"操作成功",
        "data":{
            "no_nosim_alert":true|false,     // Suppress the "No SIM" alert (default: false)
            "no_low_power_alert":true|false, // Suppress the "Low Battery" alert (default: false)
            "no_idle":true|false,            // Insomnia mode: keep device awake (effective only when remote service is enabled)
            "script_on_daemon":true|false,   // Daemon mode: restart the last running script when the service restarts after an abnormal exit (default: false)
            "script_end_hint":true|false     // Display a notification when a script stops (default: false)
        }
    }
    ```

---

Source: [Get Value of a Process Dictionary Entry](https://xxtouch.app/en/docs/OpenAPI/Control/proc_get.md)
Path: OpenAPI/Control/proc_get.md

# Get Value of a Process Dictionary Entry

- Description

    ```http
    POST /proc_get HTTP/1.1

    {"key":"[key]"}
    ```

- Possible Responses

    ```json
    {"code":0,"key":"[key]","value":"[value]"}
    ```
    ```json
    {"code":1,"message":"操作失败"}
    ```

- Notes
    - Read the value of the entry keyed by `[key]` in the running XXTouch service process dictionary on the device
    - If the entry keyed by `[key]` has no value, the request fails

- Example

    If the device script runs:
    ```lua
    proc_put("username", "test_user")
    ```

    Send this request to the device:
    ```http
    POST /proc_get HTTP/1.1
    Content-Length: 18

    {"key":"username"}
    ```

    The device returns:
    ```json
    {"code":0,"key":"username","value":"test_user"}
    ```

---

Source: [Create a Directory](https://xxtouch.app/en/docs/OpenAPI/FileSystem/mkdir.md)
Path: OpenAPI/FileSystem/mkdir.md

# Create a Directory

- Description

    ```http
    POST /mkdir HTTP/1.1

    {"directory":"directory name"}
    ```

- Possible Responses

    ```json
    {"code":0,"message":"操作成功"}
    ```
    ```json
    {"code":1,"message":"操作失败","detail":"detailed error message"}
    ```
    ```json
    {"code":8,"message":"参数错误"}
    ```

- Notes
    - The root directory for file operations via this API is `/var/mobile/Media/1ferver/`

---

Source: [Shutdown](https://xxtouch.app/en/docs/OpenAPI/System/halt.md)
Path: OpenAPI/System/halt.md

# Shutdown

- Description

    ```http
    POST /halt HTTP/1.1
    ```

- Possible Responses

    ```json
    {"code":0,"message":"操作成功"}
    ```

---

Source: [Set User Preferences](https://xxtouch.app/en/docs/OpenAPI/Config/set_user_conf.md)
Path: OpenAPI/Config/set_user_conf.md

# Set User Preferences

- Description

    ```http
    POST /set_user_conf HTTP/1.1

    {
        "no_nosim_alert":true|false,     // Suppress the "No SIM" alert (default: false)
        "no_low_power_alert":true|false, // Suppress the "Low Battery" alert (default: false)
        "no_idle":true|false,            // Insomnia mode: keep device awake (effective only when remote service is enabled)
        "script_on_daemon":true|false,   // Daemon mode: restart the last running script when the service restarts after an abnormal exit (default: false); cannot be enabled while a script is running
        "script_end_hint":true|false     // Display a notification when a script stops (default: false)
    }
    ```

- Possible Responses

    ```json
    {"code":0,"message":"操作成功"}
    ```
    ```json
    {"code":1,"message":"脚本运行的过程中无法做出该操作"}
    ```
    ```json
    {"code":8,"message":"参数错误"}
    ```

---

Source: [Push Entry into Process Dictionary Queue](https://xxtouch.app/en/docs/OpenAPI/Control/proc_queue_push.md)
Path: OpenAPI/Control/proc_queue_push.md

# Push Entry into Process Dictionary Queue

- Description

    ```http
    POST /proc_queue_push HTTP/1.1

    {"key":"[key]","value":"[value]"}
    ```

- Possible Responses

    ```json
    {"code":0,"message":"操作成功","size":10} // size is the current number of entries in the queue
    ```

- Notes
    - Push an entry with value `[value]` into the process dictionary queue identified by `[key]`
    - `[key]` identifies the queue and is used to retrieve values
    - `[value]` is a string

---

Source: [Remove a Directory](https://xxtouch.app/en/docs/OpenAPI/FileSystem/rmdir.md)
Path: OpenAPI/FileSystem/rmdir.md

# Remove a Directory

- Description

    ```http
    POST /rmdir HTTP/1.1

    {"directory":"directory name"}
    ```

- Possible Responses

    ```json
    {"code":0,"message":"操作成功"}
    ```
    ```json
    {"code":8,"message":"参数错误"}
    ```

- Notes
    - The root directory for file operations via this API is `/var/mobile/Media/1ferver/`
    - This endpoint removes the directory regardless of whether it is empty

---

Source: [Refresh UI Cache](https://xxtouch.app/en/docs/OpenAPI/System/uicache.md)
Path: OpenAPI/System/uicache.md

# Refresh UI Cache

- Description

    ```http
    POST /uicache HTTP/1.1
    ```

- Possible Responses

    ```json
    {"code":0,"message":"操作成功"}
    ```

---

Source: [Suppress "No SIM" Alert Switch](https://xxtouch.app/en/docs/OpenAPI/Config/set_no_nosim_alert.md)
Path: OpenAPI/Config/set_no_nosim_alert.md

# Suppress "No SIM" Alert Switch

- Description

    Suppress the "No SIM" alert
    ```http
    POST /set_no_nosim_alert_on HTTP/1.1
    ```
    Do not suppress the "No SIM" alert
    ```http
    POST /set_no_nosim_alert_off HTTP/1.1
    ```

- Possible Responses

    ```json
    {"code":0,"message":"操作成功"}
    ```

- Notes
    - Only effective on fully jailbroken iOS 12 and below

---

Source: [Pop Entry from Process Dictionary Queue](https://xxtouch.app/en/docs/OpenAPI/Control/proc_queue_pop.md)
Path: OpenAPI/Control/proc_queue_pop.md

# Pop Entry from Process Dictionary Queue

- Description

    ```http
    POST /proc_queue_pop HTTP/1.1

    {"key":"[key]"}
    ```

- Possible Responses

    ```json
    {"code":0,"message":"操作成功","key":"[key]","value":"[value]"}
    ```

- Notes
    - Pop one value from the process dictionary queue identified by `[key]`. If the queue is empty, an empty string is returned.
    - `[key]` identifies the queue and is used to retrieve values.

---

Source: [Suppress "Low Battery" Alert Switch](https://xxtouch.app/en/docs/OpenAPI/Config/set_no_low_power_alert.md)
Path: OpenAPI/Config/set_no_low_power_alert.md

# Suppress "Low Battery" Alert Switch

- Description

    Disable the "Low Battery" alert
    ```http
    POST /set_no_low_power_alert_on HTTP/1.1
    ```
    Enable the "Low Battery" alert
    ```http
    POST /set_no_low_power_alert_off HTTP/1.1
    ```

- Possible Responses

    ```json
    {"code":0,"message":"操作成功"}
    ```

- Notes
    - Only effective on fully jailbroken iOS 12 and below

---

Source: [Pop All Entries from a Process Dictionary Queue](https://xxtouch.app/en/docs/OpenAPI/Control/proc_queue_clear.md)
Path: OpenAPI/Control/proc_queue_clear.md

# Pop All Entries from a Process Dictionary Queue

- Description

    ```http
    POST /proc_queue_clear HTTP/1.1

    {"key":"[key]"}
    ```

- Possible Responses

    ```json
    {"code":0,"message":"操作成功","key":"[key]","values":["item 1", "item 2", "..."]}
    ```

- Notes
    - Pop all values from the process dictionary queue identified by `[key]`.
    - `[key]` identifies the queue and is used to retrieve values.

---

Source: [Rename a File or Directory (RAW)](https://xxtouch.app/en/docs/OpenAPI/FileSystem/rename_file.md)
Path: OpenAPI/FileSystem/rename_file.md

# Rename a File or Directory (RAW)

- Description

    ```http
    POST /rename_file HTTP/1.1

    {"filename":"old name","newfilename":"new name"}
    ```

- Possible Responses

    ```json
    {"code":0,"message":"操作成功"}
    ```
    ```json
    {"code":1,"message":"操作失败","detail":"specific error message"}
    ```
    ```json
    {"code":4,"message":"文件或目录不存在"}
    ```
    ```json
    {"code":11,"message":"文件或目录已存在"}
    ```
    ```json
    {"code":8,"message":"参数错误"}
    ```

- Notes
    - The root directory for file operations via this API is `/var/mobile/Media/1ferver/`

---

Source: [Erase All Content and Settings](https://xxtouch.app/en/docs/OpenAPI/System/clear_all.md)
Path: OpenAPI/System/clear_all.md

# Erase All Content and Settings

- Description

    ```http
    POST /clear_all HTTP/1.1
    ```

- Possible Responses

    ```json
    {"code":0,"message":"清理已经完成"}
    ```

---

Source: [Suppress "Use Push Notifications to Connect to iTunes" Alert Switch](https://xxtouch.app/en/docs/OpenAPI/Config/set_no_need_pushid_alert.md)
Path: OpenAPI/Config/set_no_need_pushid_alert.md

# Suppress "Use Push Notifications to Connect to iTunes" Alert Switch

- Description

    Suppress the alert
    ```http
    POST /set_no_need_pushid_alert_on HTTP/1.1
    ```
    Do not suppress the alert
    ```http
    POST /set_no_need_pushid_alert_off HTTP/1.1
    ```

- Possible Responses

    ```json
    {"code":0,"message":"操作成功"}
    ```

- Notes
    - Only effective on fully jailbroken iOS 12 and below

---

Source: [Delete a File or Empty Directory (RAW)](https://xxtouch.app/en/docs/OpenAPI/FileSystem/remove_file.md)
Path: OpenAPI/FileSystem/remove_file.md

# Delete a File or Empty Directory (RAW)

- Description

    ```http
    POST /remove_file HTTP/1.1

    {"filename":"file name"}
    ```

- Possible Responses

    ```json
    {"code":0,"message":"操作成功"}
    ```
    ```json
    {"code":1,"message":"操作失败","detail":"specific error message"}
    ```
    ```json
    {"code":4,"message":"文件或目录不存在"}
    ```
    ```json
    {"code":8,"message":"参数错误"}
    ```

- Notes
    - The root directory for file operations via this API is `/var/mobile/Media/1ferver/`

---

Source: [Clear App Data](https://xxtouch.app/en/docs/OpenAPI/System/clear_app_data.md)
Path: OpenAPI/System/clear_app_data.md

# Clear App Data

- Description

    ```http
    POST /clear_app_data HTTP/1.1

    {"bid":"Bundle ID"}
    ```

- Possible Responses

    ```json
    {"code":0,"message":"清理已经完成"}
    ```
    ```json
    {"code":1,"message":"操作失败"}
    ```
    ```json
    {"code":8,"message":"参数错误"}
    ```
    ```json
    {"code":11,"message":"这个应用程序的存档不能清理"}
    ```

---

Source: [Set Device Name](https://xxtouch.app/en/docs/OpenAPI/Config/set_device_name.md)
Path: OpenAPI/Config/set_device_name.md

# Set Device Name

- Description

    ```http
    POST /set_device_name HTTP/1.1

    {"name":"Device Name"}
    ```

- Possible Responses

    ```json
    {"code":0,"message":"操作成功"}
    ```
    ```json
    {"code":8,"message":"参数错误"}
    ```

---

Source: [Read a File (RAW)](https://xxtouch.app/en/docs/OpenAPI/FileSystem/read_file.md)
Path: OpenAPI/FileSystem/read_file.md

# Read a File (RAW)

## Streamed Read

- Description

    ```http
    GET /read_file?filename=[URL-encoded filename] HTTP/1.1
    ```

    - Optional query `md5=1`: adds `Content-MD5` (Base64) to the response headers

- Possible Responses

    - Success: HTTP 200, response body is the raw file bytes (not base64-encoded)
    - Failure:
        - HTTP 404 + `{"message":"File not found"}` (file does not exist or `filename` missing)
        - HTTP 415 + `{"message":"File is a directory"}` (path points to a directory)

- Python 3.x example for streaming a script file (requires `requests`):

    ```python
    # -*- coding: utf-8 -*-
    import requests

    with requests.get(
        "http://192.168.31.72:46952/read_file",
        params={"filename": "lua/scripts/123.lua", "md5": 1},
        stream=True,
        timeout=30,
    ) as r:
        r.raise_for_status()
        with open("r:/123.lua", "wb") as f:
            for chunk in r.iter_content(chunk_size=8192):
                if chunk:
                    f.write(chunk)
            print("Content-MD5:", r.headers.get("Content-MD5"))
    ```

## Base64 Read

- Description

    ```http
    POST /read_file HTTP/1.1

    {"filename":"file name"}
    ```

- Possible Responses

    ```json
    {"code":0,"message":"操作成功","data":"base64-encoded file content"}
    ```
    ```json
    {"code":4,"message":"无法读取文件"}
    ```
    ```json
    {"code":8,"message":"参数错误"}
    ```

- Python 3.x example to read a script file from the device (requires `requests`):

    ```python
    # -*- coding: utf-8 -*-
    import base64
    import requests

    resp = requests.post(
        "http://192.168.31.72:46952/read_file",
        json={"filename": "lua/scripts/123.lua"},
        timeout=30,
    )

    print(resp.status_code, resp.reason)  # 200 OK on success
    if resp.status_code == 200:
        ret = resp.json()
        print(ret.get("message"))
        if ret.get("code") == 0:
            print(base64.b64decode(ret["data"]).decode("utf-8"))
    else:
        print(resp.text)
    ```

## Notes

- The root directory for both read methods is `/var/mobile/Media/1ferver/`
- The streamed read endpoint is available in versions after `2025-07-11`

---

Source: [Import an Image to Photos](https://xxtouch.app/en/docs/OpenAPI/System/image_to_album.md)
Path: OpenAPI/System/image_to_album.md

# Import an Image to Photos

- Description

    ```http
    POST /image_to_album HTTP/1.1

    [image binary data]
    ```

- Possible Responses

    ```json
    {"code":0,"message":"操作成功"}
    ```
    ```json
    {"code":1,"message":"操作失败"}
    ```

- Computer-side example (Python 3.x):

    ```python
    # -*- coding: utf-8 -*-
    import http.client
    import json

    imgf = open('r:/1.png', 'rb')  # image file path
    imgdata = imgf.read()

    conn = http.client.HTTPConnection("192.168.31.72:46952")  # device address and port
    conn.request("POST", "/image_to_album", imgdata)

    response = conn.getresponse()

    if response.status == 200:
        ret = json.loads(response.read().decode('utf-8'))  # explicitly decode as UTF-8
        print(ret['message'])
    else:
        print(response.status, response.reason)
        print(response.read().decode('utf-8'))  # explicitly decode as UTF-8

    conn.close()
    ```

- Notes
    - Supported formats: PNG, JPG

---

Source: [Set Screen Brightness](https://xxtouch.app/en/docs/OpenAPI/Config/set_brightness.md)
Path: OpenAPI/Config/set_brightness.md

# Set Screen Brightness

- Description

    ```http
    POST /set_brightness HTTP/1.1

    {"level": 0.5}
    ```

    > `level`: number in the range 0.0\~1.0

- Possible Responses

    ```json
    {"code":0,"message":"操作成功"}
    ```
    ```json
    {"code":8,"message":"参数错误"}
    ```

---

Source: [Write a File (RAW)](https://xxtouch.app/en/docs/OpenAPI/FileSystem/write_file.md)
Path: OpenAPI/FileSystem/write_file.md

# Write a File (RAW)

## Streamed Write

- Description

    ```http
    PUT /write_file?filename=[URL-encoded filename] HTTP/1.1

    [file data]
    ```

    - Accepts raw file bytes (not base64-encoded), suitable for large uploads
    - Overwrites the target if it already exists

- Possible Responses

    - Success: HTTP 204, no response body
    - Failure:
        - HTTP 400 + `{"message":"invalid path"}` (missing `filename` or invalid path)
        - HTTP 404 + `{"message":"invalid path"}` (cannot create the target path)
        - HTTP 500 + `{"message":"…"}`

- Python 3.x example for streaming content to a script file (requires `requests`):

    ```python
    # -*- coding: utf-8 -*-
    import requests

    with open("r:/123.lua", "rb") as f:
        resp = requests.put(
            "http://192.168.31.72:46952/write_file",
            params={"filename": "lua/scripts/123.lua"},
            data=f,
            timeout=30,
        )

    print(resp.status_code, resp.reason)  # 204 No Content on success
    if resp.status_code != 204:
        print(resp.text)
    ```

## Base64 Write

- Description

    ```http
    POST /write_file HTTP/1.1

    {"filename":"file name","data":"base64-encoded content"}
    ```

- Possible Responses

    ```json
    {"code":0,"message":"操作成功"}
    ```
    ```json
    {"code":4,"message":"无法写入文件"}
    ```

- Python 3.x example to write content to a script file (requires `requests`):

    ```python
    # -*- coding: utf-8 -*-
    import base64
    import requests

    with open('r:/123.lua', 'rb') as f:  # script file path, read raw bytes directly
        resp = requests.post(
            "http://192.168.31.72:46952/write_file",
            json={
                "filename": "lua/scripts/123.lua",
                "data": base64.b64encode(f.read()).decode('utf-8')
            },
            timeout=30,
        )

    print(resp.status_code, resp.reason)  # 200 OK on success
    print(resp.text)
    ```

## Notes

- The root directory for both write methods is `/var/mobile/Media/1ferver/`
- The streamed write endpoint is available in versions after `2025-07-11`

---

Source: [Self-Update](https://xxtouch.app/en/docs/OpenAPI/System/update_deb.md)
Path: OpenAPI/System/update_deb.md

# Self-Update

- Description

    ```http
    POST /update_deb HTTP/1.1

    [deb binary data]
    ```

- Possible Responses

    ```json
    {"code":0,"message":"操作成功"}
    ```
    ```json
    {"code":1,"message":"操作失败"}
    ```

- Notes
    - This endpoint does not return the installation result
    - "Success" only means the upload succeeded; installation is asynchronous
    - This endpoint may also install other `.deb` packages, but compatibility is not guaranteed
    - The TrollStore build cannot install `.deb` packages; use TrollStore to install `.tipa` files instead

---

Source: [Set System Volume](https://xxtouch.app/en/docs/OpenAPI/Config/set_volume.md)
Path: OpenAPI/Config/set_volume.md

# Set System Volume

- Description

    ```http
    POST /set_volume HTTP/1.1

    {"level": 0.5}
    ```

    > `level`: number in the range 0.0\~1.0

- Possible Responses

    ```json
    {"code":0,"message":"操作成功"}
    ```
    ```json
    {"code":8,"message":"参数错误"}
    ```

---

Source: [Download a File (Redirect)](https://xxtouch.app/en/docs/OpenAPI/FileSystem/download_file.md)
Path: OpenAPI/FileSystem/download_file.md

# Download a File (Redirect)

- Description

    ```http
    GET /download_file?filename=[UTF-8 URI-encoded file path]
    ```

- Possible Responses

    200
    ```
    [binary file content]
    ```
    400
    ```json
    {"code":4,"message":"文件或目录不存在"}
    ```

- Notes
    - The root directory for file operations via this API is `/var/mobile/Media/1ferver/`
    - Absolute paths are supported. If the first character of the path is `/`, it is treated as an absolute path

---

Source: [Enable Remote Access](https://xxtouch.app/en/docs/OpenAPI/System/open_remote_access.md)
Path: OpenAPI/System/open_remote_access.md

# Enable Remote Access

- Description

    ```http
    POST /open_remote_access HTTP/1.1
    ```

- Possible Responses

    ```json
    {"code":0,"message":"操作成功"}
    ```
    ```json
    {"code":1,"message":"操作失败"}
    ```

- Notes
    - This API can only be called on the device itself

---

Source: [Disable Remote Access](https://xxtouch.app/en/docs/OpenAPI/System/close_remote_access.md)
Path: OpenAPI/System/close_remote_access.md

# Disable Remote Access

- Description

    ```http
    POST /close_remote_access HTTP/1.1
    ```

- Possible Responses

    ```json
    {"code":0,"message":"操作成功"}
    ```

---

Source: [Check Remote Access Status](https://xxtouch.app/en/docs/OpenAPI/System/is_remote_access_opened.md)
Path: OpenAPI/System/is_remote_access_opened.md

# Check Remote Access Status

- Description

    ```http
    POST /is_remote_access_opened HTTP/1.1
    ```

- Possible Responses

    ```json
    {"code":0,"message":"操作成功","data":{"opened":true|false}}
    ```

- Notes
    - This API can only be called on the device itself

---

Source: [XPP Script Bundle](https://xxtouch.app/en/docs/XPP/index.md)
Path: XPP/README.md

# XPP Script Bundle

Before XXTouch 1.2, we used Lua as the development language with `.lua` as the source code format and `.xxt` as the compiled/encrypted executable script format. However, a single source file or executable script often depends on modules, configuration, and assets, making distribution, versioning, and resource usage inconvenient. We therefore introduced the XPP script bundle and the XPA archive format.

---

- [XPP Format](Layout)
  - [Info (Metadata)](Layout/Info)
    - [BundleIdentifier](Layout/Info/BundleIdentifier.md)
    - [BundleVersion](Layout/Info/BundleVersion.md)
    - [BundleName](Layout/Info/BundleName.md)
    - [BundleDisplayName](Layout/Info/BundleDisplayName.md)
    - [BundleIconFile](Layout/Info/BundleIconFile.md)
    - [Executable](Layout/Info/Executable.md)
    - [MainInterfaceFile](Layout/Info/MainInterfaceFile.md)
    - [MinimumSystemVersion/MaximumSystemVersion](Layout/Info/SystemVersion.md)
    - [MinimumXXTVersion](Layout/Info/MinimumXXTVersion.md)
    - [SupportedResolutions](Layout/Info/SupportedResolutions.md)
    - [PackageControl](Layout/Info/PackageControl.md)
  - [Localizable](Layout/Localizable.md)
- [XPA Packaging Format](XPA.md)

---

Source: [Metadata](https://xxtouch.app/en/docs/XPP/Layout/Info/index.md)
Path: XPP/Layout/Info/README.md

# Metadata

An XPP bundle must contain a script named `Info.lua` that returns a Lua table constant describing the bundle metadata. It should not contain executable logic beyond constants.

A typical `Info.lua` example:

```lua
return {
    BundleIdentifier = "com.yourcompany.yourscript";
    BundleVersion = "0.0.1";
    BundleName = "Your Name";
    BundleDisplayName = "Your Display Name";
    BundleIconFile = "appicon.png";
    Executable = "xui-script.lua";
    MainInterfaceFile = "xui-demo.xui";
    MinimumSystemVersion = "10.0";
    MaximumSystemVersion = "10.2";
    MinimumXXTVersion = "1.1.2";
    SupportedResolutions = {
        { width = 640; height = 1136; };
    };
    PackageControl = {
        AuthorName = "i_82";
        AuthorEmail = "i.82@me.com";
        Description = "";
        Homepage = "https://82flex.com";
    };
};
```

The returned table usually contains the following keys. See subpages for details:

| Key | Required | Recommended | Description |
|-----|:-------:|:-----------:|-------------|
|BundleIdentifier|*|*|Unique identifier|
|BundleVersion|*|*|Version|
|BundleName|*|*|Name|
|Executable||*|Entry script filename ( .lua, .xxt )|
|BundleDisplayName||*|Display name|
|BundleIconFile||*|App icon|
|MainInterfaceFile||*|XUI entry config ( .xui, .xuic )|
|MinimumSystemVersion|||Minimum iOS version|
|MaximumSystemVersion|||Maximum iOS version|
|MinimumXXTVersion|||Minimum XXTouch version|
|SupportedResolutions|||Supported device resolutions|
|PackageControl|||Additional information|

You should complete these as much as possible. A good display name, icon, and configuration UI improve the look-and-feel and acceptance of your script.

In scripts, you can read constants from `Info.lua` via the [XPP bundle module](/en/docs/handbook/xpp/index.md).


**Which script formats does XPP support?**

Executable script formats supported in XPP bundles are `.lua` and `.xxt`. Scripts access resources/configuration from the bundle via relative paths. To specify the entry script, see [Executable](/en/docs/XPP/Layout/Info/Executable.md).

**How to specify the XPP configuration UI?**

To specify the configuration page opened from XXTouch, set [MainInterfaceFile](/en/docs/XPP/Layout/Info/MainInterfaceFile.md). To write the config UI, see the [XUI Handbook](/en/docs/XUI.md).

**How to manage resources in XPP?**

- Put scripts/resources/modules/data inside the XPP directory and access them via relative paths.
- Do not write temporary files/data into the XPP bundle at runtime; use XXTouch cache/temp directories instead.

In scripts, you can get resource paths from the [XPP bundle module](/en/docs/handbook/xpp/index.md).

---

Source: [XPP Format](https://xxtouch.app/en/docs/XPP/Layout/index.md)
Path: XPP/Layout/README.md

# XPP Format

XPP (a “script app bundle”) is a bundle structure that XXTouch can parse, display, and execute, presented to users as a single file. In fact, this “file” is a directory with the `.xpp` extension. Its structure is as follows:

| File | Description |
|------|-------------|
|`Info.lua`|Structured metadata storing the bundle configuration. XXTouch relies on this to recognize XPP and related files.|
|Executable scripts|Each bundle must contain at least one executable script (`.xxt`, `.lua`).|
|Interface config|Optional. XUI configs (`.xui`, `.xuic`) that provide a settings UI.|
|Resources|Optional. Assets required by the scripts, such as images, icons, audio, localized strings, configs, and other data. Many resources can be localized while others are shared.|

:::info What is a Bundle?

A bundle is a directory with a specific structure and extension that groups related resources (executables, localized strings, images, etc.) into a single conceptual unit. Bundles behave like files to reduce the risk of accidental modification or loss of internal files, and simplify resource organization.

:::

![IMG_2723.jpg](XPPScreenshots/IMG_2723.jpg)

---

Source: [BundleDisplayName (Display Name)](https://xxtouch.app/en/docs/XPP/Layout/Info/BundleDisplayName.md)
Path: XPP/Layout/Info/BundleDisplayName.md

# BundleDisplayName (Display Name)

Display name shown in the XXTouch app's script list. It can be longer than 16 characters and is used only for display purposes; do not use it for logic.

If not set, the value of BundleName (short name) is used.

---

Source: [BundleIconFile (Icon File)](https://xxtouch.app/en/docs/XPP/Layout/Info/BundleIconFile.md)
Path: XPP/Layout/Info/BundleIconFile.md

# BundleIconFile (Icon File)

Icon file shown in the XXTouch app’s script list. Provide the relative path inside the bundle. Must be a `.png` file. If the base name is `appicon.png`, you must include:

| Filename | Size |
|----------|------|
|appicon.png|64 × 64|
|appicon@2x.png|128 × 128|
|appicon@3x.png|192 × 192|

If not set, the default icon is used.

---

Source: [BundleIdentifier (Bundle Identifier)](https://xxtouch.app/en/docs/XPP/Layout/Info/BundleIdentifier.md)
Path: XPP/Layout/Info/BundleIdentifier.md

# BundleIdentifier (Bundle Identifier)

Uniquely identifies an XPP bundle. Once set, it must remain unchanged throughout the bundle’s lifetime.

The identifier must be a Uniform Type Identifier (UTI) style string using only letters (`A-Z`, `a-z`), digits (`0-9`), hyphen `-`, and dot `.`. It usually follows reverse-DNS style. For example, for domain `82flex.com` and script name `Hello`, use `com.82flex.hello`.

---

Source: [BundleName (Short Name)](https://xxtouch.app/en/docs/XPP/Layout/Info/BundleName.md)
Path: XPP/Layout/Info/BundleName.md

# BundleName (Short Name)

Short name. It should not exceed 16 characters and may be used by scripts for display and lookup, such as in menus and notifications.

---

Source: [BundleVersion (Bundle Version)](https://xxtouch.app/en/docs/XPP/Layout/Info/BundleVersion.md)
Path: XPP/Layout/Info/BundleVersion.md

# BundleVersion (Bundle Version)

Version string indicating each release iteration:

    1.1.0
    major.minor.patch

All segments are integers separated by dots. The patch segment may be omitted (defaults to 0):

    1.1
    major.minor

Version must monotonically increase over time. Compare by major, then minor, then patch.

---

Source: [Executable (Entry Script)](https://xxtouch.app/en/docs/XPP/Layout/Info/Executable.md)
Path: XPP/Layout/Info/Executable.md

# Executable (Entry Script)

Entry script filename relative to the bundle. Must be `.lua` or `.xxt`.

If not set, the XPP will not show a launch button and cannot be started directly. If `MainInterfaceFile` is set, tapping opens the configuration UI. You can start different entry scripts from the XUI config.

---

Source: [MainInterfaceFile (XUI Entry File)](https://xxtouch.app/en/docs/XPP/Layout/Info/MainInterfaceFile.md)
Path: XPP/Layout/Info/MainInterfaceFile.md

# MainInterfaceFile (XUI Entry File)

XUI configuration file opened when configuring the bundle from XXTouch. Must be `.xui` or `.xuic`. The `.xuic` format is an encrypted variant of `.xui`, which you can generate in-app.

If not set, the XPP will not show a configuration button.

See: [XUI Handbook](/en/docs/XUI.md)

---

Source: [MinimumXXTVersion (Minimum XXTouch Service Version)](https://xxtouch.app/en/docs/XPP/Layout/Info/MinimumXXTVersion.md)
Path: XPP/Layout/Info/MinimumXXTVersion.md

# MinimumXXTVersion (Minimum XXTouch Service Version)

Minimum XXTouch service version required. If the requirement is not met, the runtime displays a compatibility warning.

If not set, defaults to being compatible with all XXTouch v1.2-1 and later.

Get the current XXTouch version in a script:

```lua
xver = sys.xtversion()
```

---

Source: [PackageControl (Additional Info)](https://xxtouch.app/en/docs/XPP/Layout/Info/PackageControl.md)
Path: XPP/Layout/Info/PackageControl.md

# PackageControl (Additional Info)

Dictionary for author, publisher, release time, copyright, and other package information. Supported keys:

| Key | Description |
|-----|-------------|
|AuthorName|Author name|
|AuthorEmail|Author email|
|Homepage|Homepage URL|
|Description|Description|
|Category|Category|
|Tags|Tags|
|Copyright|Copyright|

These will be shown in project properties and during installation.

---

Source: [SupportedDeviceTypes (Supported Device Types)](https://xxtouch.app/en/docs/XPP/Layout/Info/SupportedDeviceTypes.md)
Path: XPP/Layout/Info/SupportedDeviceTypes.md

# SupportedDeviceTypes (Supported Device Types)

Array of supported device type codes. If the current device type is not in the array, installation/configuration/runtime will warn about incompatibility.

If not set, all device types are supported by default.

Get the device type in a script:

```lua
dtype = device.type()
```

---

Source: [SupportedResolutions (Supported Physical Screen Sizes)](https://xxtouch.app/en/docs/XPP/Layout/Info/SupportedResolutions.md)
Path: XPP/Layout/Info/SupportedResolutions.md

# SupportedResolutions (Supported Physical Screen Sizes)

Array of supported device physical screen sizes. If the current device screen size is not in the array, installation/configuration/runtime will warn about incompatibility.

If not set, all screen sizes are supported by default.

Get the physical screen size in a script:

```lua
width, height = screen.size()
```

---

Source: [MinimumSystemVersion/MaximumSystemVersion (iOS Version Range)](https://xxtouch.app/en/docs/XPP/Layout/Info/SystemVersion.md)
Path: XPP/Layout/Info/SystemVersion.md

# MinimumSystemVersion/MaximumSystemVersion (iOS Version Range)

Minimum/maximum supported iOS versions. If the current iOS version is outside this range, installation/configuration/runtime will warn about incompatibility.

Get the current system version in a script:

```lua
ver = sys.version()
```

---

Source: [Localization](https://xxtouch.app/en/docs/XPP/Layout/Localizable.md)
Path: XPP/Layout/Localizable.md

# Localization

XPP supports localized metadata and localized resources. The strategy matches Apple’s iOS localization. Place `Info.plist` or `.strings` files inside language folders ending in `.lproj` to enable multiple languages. For implementation details, refer to Apple’s app localization docs.

---

Source: [XPA Packaging Format](https://xxtouch.app/en/docs/XPP/XPA.md)
Path: XPP/XPA.md

# XPA Packaging Format

An XPP bundle directory can be packaged into an XPA archive for distribution. Users install the XPA to restore it back into an XPP bundle.

XPA is essentially a `.zip` file with a very simple structure:

```
Demo.xpa (zipped)
    - Payload
        - A-Script-Bundle.xpp
```

Place your prepared `.xpp` bundle inside an empty directory named `Payload`, zip the `Payload` directory, and rename the zip file extension to `.xpa`.

---

Source: [XUI Library Index](https://xxtouch.app/en/docs/XUI/index.md)
Path: XUI/README.md

# XUI Library Index

---

- [Preface](START.md)
- [Demo](Demo/)
- [Creation](Creation/README.md)
    - [Root](Creation/Root.md)
    - [Theme](Creation/Theme.md)
    - [General Properties](Creation/General.md)
    - [Read Settings](Creation/ReadSettings.md)
- [Components](Modules/README.md)
    - [Group](Modules/Group.md)
    - [Link (Sub-page)](Modules/Link.md)
    - [Switch](Modules/Switch.md)
    - [Button](Modules/Button.md)
    - [TextField](Modules/TextField.md)
    - [Radio / Checkbox](Modules/Radio_Checkbox.md)
    - [Segment](Modules/Segment.md)
    - [Option](Modules/Option.md)
    - [MultipleOption](Modules/MultipleOption.md)
    - [OrderedOption](Modules/OrderedOption.md)
    - [EditableList](Modules/EditableList.md)
    - [Slider](Modules/Slider.md)
    - [Stepper](Modules/Stepper.md)
    - [DateTime](Modules/DateTime.md)
    - [TitleValue (Key-Value Display; Snippet Picker)](Modules/TitleValue.md)
    - [StaticText](Modules/StaticText.md)
    - [Textarea](Modules/Textarea.md)
    - [Image / AnimatedImage](Modules/Image_AnimatedImage.md)
    - [File](Modules/File.md)
    - [About](Modules/About.md)
- [APIs available to XUI](Internal_Lua_Module.md)
- [Code Snippets](Snippet/README.md)
    - [Create Snippet](Snippet/Creation.md)
    - [App Picker](Snippet/app.md)
    - [Virtual Key Picker](Snippet/key.md)
    - [Location Picker](Snippet/loc.md)
    - [Image Position & Color Picker](Snippet/poscolor.md)
    - [Image Rect Picker](Snippet/rect.md)

---

Source: [Demo](https://xxtouch.app/en/docs/XUI/Demo/index.md)
Path: XUI/Demo/README.md

# Demo

![XUI-Light.png](XUI-Light.png)

Scan with XXTouch to download the demo bundle.
![XUIDemoQRCode.png](XUIDemoQRCode.png)

---

Source: [Creation](https://xxtouch.app/en/docs/XUI/Creation/index.md)
Path: XUI/Creation/README.md

# Creation

A `.xui` script is a specially formatted `.lua` script (UTF-8 encoded plain text). To build an XUI layout, the Lua file must return a table describing components and their properties. A `.xui` can be encrypted in-app into a `.xuic` to prevent tampering.

While possible, using `.json` or `.plist` to create XUI layouts is not recommended.

---

Source: [Components](https://xxtouch.app/en/docs/XUI/Modules/index.md)
Path: XUI/Modules/README.md

# Components

- [Group](Group.md)
- [Link (Sub-page)](Link.md)
- [Switch](Switch.md)
- [Button](Button.md)
- [TextField](TextField.md)
- [Radio / Checkbox](Radio_Checkbox.md)
- [Segment](Segment.md)
- [Option](Option.md)
- [MultipleOption](MultipleOption.md)
- [OrderedOption](OrderedOption.md)
- [EditableList](EditableList.md)
- [Slider](Slider.md)
- [Stepper](Stepper.md)
- [DateTime](DateTime.md)
- [TitleValue (Key-Value Display; Snippet Picker)](TitleValue.md)
- [StaticText](StaticText.md)
- [Textarea](Textarea.md)
- [Image / AnimatedImage](Image_AnimatedImage.md)
- [File](File.md)
- [About](About.md)

---

Source: [Code Snippets](https://xxtouch.app/en/docs/XUI/Snippet/index.md)
Path: XUI/Snippet/README.md

# Code Snippets

A snippet template `.snippet` is a special Lua file that describes how to generate plain-text code or other objects from the results of one or more "snippet pickers". Generated objects can be saved into XUI configuration, and text results can be inserted quickly in the code editor.

"Snippet pickers" are a set of predefined pickers used to produce inputs for a snippet. Supported picker types:

- Single App Picker `app`
- Multiple Apps Picker `apps`
- Location Picker `loc`
- Virtual Key Picker `key`
- Single Image Position Picker `pos`
- Single Image Color Picker `color`
- Single Image Position & Color Picker `poscolor`
- Multiple Image Positions & Colors Picker `poscolors`
- Image Rect Picker `rect`

- [Create Snippet](Creation.md)
- [App Picker](app.md)
- [Virtual Key Picker](key.md)
- [Location Picker](loc.md)
- [Image Position & Color Picker](poscolor.md)
- [Image Rect Picker](rect.md)

---

Source: [Group](https://xxtouch.app/en/docs/XUI/Modules/Group.md)
Path: XUI/Modules/Group.md

# Group

Displays a grouped section containing all components until the next `Group`. It is commonly used to separate features or add supporting descriptions. The first item in the list must be a `Group`; otherwise, XUI automatically inserts one at the top.

|Key|Type|Description|Required|Default|Min Version|
|---|---|---|---|---|---|
|label|string|Group title|Localizable|""|–|
|footerText|string|Small text after this group|Localizable|""|–|

This component does not support `icon`/`height`.

# Theme

|Theme Key|Type|Description|
|---|---|---|
|groupHeaderTextColor|Color|Header title color (`label`)|
|groupFooterTextColor|Color|Footer text color (`footerText`)|
|groupHeaderBackgroundColor|Color|Header background color|
|groupFooterBackgroundColor|Color|Footer background color|

## Example

```lua
-- Group
{
    cell = "Group";
    label = "Switches";
    footerText = "This is a group of switches";
};
-- The next two components are switches in this group
{
    default = true;
    label = "Enable feature";
    cell = "Switch";
    key = "enabled";
};
{
    default = false;
    label = "Switch with icon";
    cell = "Switch";
    key = "enabled1";
    icon = "res/16.png";
    readonly = true;
};
-- Another group
{
    cell = "Group";
    label = "Another Group";
};
-- ...
```

![XUI-Group.png](XUIScreenshots/XUI-Group.png)

---

Source: [Snippet Creation](https://xxtouch.app/en/docs/XUI/Snippet/Creation.md)
Path: XUI/Snippet/Creation.md

# Snippet Creation

## Create

Typically, a snippet template `.snippet` should directly return a table, for example:

```lua
return {
    name = 'Test snippet';  -- snippet name
    description = 'Used to test various pickers';  -- snippet description
    arguments = {  -- picker list
        {  -- picker 1
            type = 'app';  -- picker type
            title = 'Select App';  -- picker title
            subtitle = 'Please select an app';  -- picker subtitle
            default = 'com.xxtouch.XXTExplorer';  -- default value
        },
        {  -- picker 2
            type = 'loc';
            title = 'Select Location';
            subtitle = 'Pick any location you like';
            default = xui.get('com.darwindev.XXTExplorer', 'location1');
            -- You can use any API supported by .xui inside a .snippet
        },
        {  -- picker 3

        },
        -- ...
    };
    generator = function (...)  -- variadic generator
        -- Process parameters and return the generated result
        local result
        return result
    end;
}
```

## Root level

|Key|Type|Description|
|---|---|---|
|name|string|Snippet display name|
|description|string|Snippet description|
|arguments|array|Picker list|
|generator|function|Snippet generator|
|output|string|Standalone output filename|

`name` and `description` are shown in the file manager and the snippet entry.

`arguments` is an array containing one or more picker-parameter dictionaries. The app builds a picker queue in the specified order and guides the user to select step by step. After completion, the app passes the picker return values as variadic parameters to `generator` and returns its result.

A `.snippet` can be used standalone. If you want to allow standalone usage, set the `output` field. The text returned by `generator` will be saved to the file identified by `output` in the same directory.

## Picker parameter dictionary

|Key|Type|Description|
|---|---|---|
|type|string|Picker type|
|title|string|Picker title (shown below the picker)|
|subtitle|string|Picker subtitle (shown below the picker)|
|default|primitive|Default value|

See later sections for details about each picker type’s parameter dictionary.

## Use in XUI

If a `.snippet` is used in the XUI `TitleValue` component, you can launch the picker queue from XUI and save the result into the component’s preferences. The `.snippet` can call all XUI APIs such as `xui.get`/`xui.set`/`xpp.bundle_path`.

## Use in the code editor

Place `.snippet` files into the main directory’s `snippets` folder to be available in the app’s code editor. Tap the star icon in the keyboard toolbar to quickly generate and insert a snippet into the code being edited.

## Use as a standalone file

Set the `output` field and put the snippet into `lua/scripts` under the main directory. You can tap it in the app to start the picker queue, and the text returned by `generator` will be saved to the file specified by `output` in the same directory.

---

Source: [Preface](https://xxtouch.app/en/docs/XUI/START.md)
Path: XUI/START.md

# Preface

Before reading this guide, you should be familiar with Lua syntax and basic data types such as numbers, booleans, strings, and tables.

- XUI does not conflict with the existing dialog module or WebView UI.
- XUI provides UI extensions for the [XPP script bundle](/en/docs/XPP/index.md).

XUI provides a configuration interface in XXTouch using native iOS components. This handbook specifies how to build XUI layouts. We provide a comprehensive [demo script bundle](/en/docs/XUI/Demo/index.md) to help you understand each chapter.

XUI is part of the [XPP script bundle](/en/docs/XPP/index.md). It is used to build configuration UIs for a bundle and cannot be used standalone. To use XUI, you must [create](/en/docs/XUI/Creation/index.md) a `.xui` script (a Lua file that returns a table) inside the bundle, and set the `MainInterfaceFile` field in `Info.lua`. See [XPP](/en/docs/XPP/index.md) for details.

Configuration items can be read, written, and updated via the [XUI script configuration interface module](/en/docs/handbook/xui/index.md).

![IMG_2722.jpg](XUIScreenshots/IMG_2722.jpg)

---

Source: [Link](https://xxtouch.app/en/docs/XUI/Modules/Link.md)
Path: XUI/Modules/Link.md

# Link

Displays a submenu entry for navigating to a subpage.

|Key|Type|Description|Required|Default|Min Version|
|---|---|---|---|---|---|
|url|string|Subpage filename or URL|*|–|–|

`url` can be a normal filename, an `.xui`/`.xuic` XUI file, or a web URL. Normal files open with the default opener; `.xui`/`.xuic` files open as XUI subpages; web URLs open in the built-in browser.

## Example

```lua
{
    cell = "Group";
    label = "Sub Pages";
};
{
    url = "sub/xui-sub.xuic"; -- Path relative to the XPP root
    cell = "Link";
    label = "More component demos";
};
{
    url = "sub/xui-dynamic.xui";
    cell = "Link";
    label = "Dynamic linkage demo";
};
{
    cell = "Group";
    label = "Resource Browser";
};
{
    url = "https://xxtouch.app";
    cell = "Link";
    label = "Open XXTouch.app";
};
{
    url = "res/b6d21727a66f856f79dc9b6ef8e7b4d6.gif";
    cell = "Link";
    label = "Open an image";
};
{
    url = "res/SmartSelect.mp4";
    cell = "Link";
    label = "Open a video";
};
{
    url = "https://www.apple.com/apple-events/september-2015/";
    cell = "Link";
    label = "Online video";
};
```

![XUI-Link.png](XUIScreenshots/XUI-Link.png)

---

Source: [App Picker](https://xxtouch.app/en/docs/XUI/Snippet/app.md)
Path: XUI/Snippet/app.md

# App Picker

The App Picker provides a preview list of apps, allowing users to pick one or multiple apps.

Type `app` (single app) allows selecting one app and returns a string: the selected app’s Bundle ID.

Type `apps` (multiple apps) allows selecting multiple apps and reordering them, returning an array of strings: an ordered list of selected app Bundle IDs.

## Example

```lua
local group, name

group = 'App'
name = 'app.bundle_path(bid)'

return {
    name = string.format('%s - %s', group, name),
    description = "Get the app bundle path",
    arguments = {
        {type = 'app'},
    },
    default = "com.darwindev.XXTExplorer",  -- Default Bundle ID
    generator = function(bid)
        return string.format('app.bundle_path(%q)', bid)
    end,
}
```

![IMG_0005.PNG](XUIScreenshots/IMG_0005.PNG)

![IMG_0006.PNG](XUIScreenshots/IMG_0006.PNG)

---

Source: [Switch](https://xxtouch.app/en/docs/XUI/Modules/Switch.md)
Path: XUI/Modules/Switch.md

# Switch

Displays a toggle switch.

|Key|Type|Description|Required|Default|Min Version|
|---|---|---|---|---|---|
|negate|boolean|Invert the displayed state|–|false|–|
|trueValue|primitive|Value to save when switch is `true` (defaults to `true`)|–|true|–|
|falseValue|primitive|Value to save when switch is `false` (defaults to `false`)|–|false|–|

|Return Type|Description|
|---|---|
|primitive|Matches the switch state; if `negate` is true, the saved value is inverted. If set, `trueValue`/`falseValue` override the saved value.|

# Theme

|Theme Key|Type|Description|
|---|---|---|
|offTintColor|Color|Track color when off|
|onTintColor|Color|Track color when on|
|thumbTintColor|Color|Thumb color|

## Example

```lua
{
    default = true;
    label = "Enable feature";
    cell = "Switch";
    key = "enabled";
};
{
    default = false;
    label = "Switch with icon";
    cell = "Switch";
    key = "enabled1";
    icon = "res/16.png";
    readonly = true;
};
```

![XUI-Switch.png](XUIScreenshots/XUI-Switch.png)

---

Source: [Virtual Key Picker](https://xxtouch.app/en/docs/XUI/Snippet/key.md)
Path: XUI/Snippet/key.md

# Virtual Key Picker

Provides a list of virtual keys such as HOME, Volume +/-, Power, etc., and allows the user to pick one.

Type `key` returns a string: the code of the selected virtual key. For the full list, see [Samples and Supported Key Codes](/en/docs/handbook/key/samples.md).

## Example

```lua
local group, name

group = 'Emulation'
name = 'key.press(key)'

return {
    name = string.format('%s - %s', group, name),
    description = "Release a pressed hardware key",
    arguments = {
        {type = 'key'},
    },
    default = "HOME",
    generator = function(key)
        return string.format('key.press(%q)', key)
    end,
}
```

![IMG_0008.PNG](XUIScreenshots/IMG_0008.PNG)

---

Source: [Button](https://xxtouch.app/en/docs/XUI/Modules/Button.md)
Path: XUI/Modules/Button.md

# Button

Displays a tappable button to perform an action.

|Key|Type|Description|Required|Default|Min Version|
|---|---|---|---|---|---|
|action|string|Action identifier|*|–|–|
|args|dictionary|Arguments passed to the action|*|–|–|
|alignment|string|Text alignment|–|Left|1.2-10|

|alignment|Description|
|---|---|
|Left|Left aligned|
|Center|Centered|
|Right|Right aligned|
|Natural|Natural|
|Justified|Justified|

# Action Notes

When finished, an action may save its return value to this component’s preference pair; set `key` and `defaults` properly.

Different `action` values require different `args`.

`Reload:`

Reload all running XUI instances. Requires XXT v1.2-10+.

No parameters, no return value.

`RunCommand:`

Execute a shell command via `system`/`posix_spawn`. Requires XXT v1.2-10+.

|Key|Type|Description|Required|Default|Min Version|
|---|---|---|---|---|---|
|command|string|Command line to execute|*|–|1.2-10|

|Return Type|Description|
|---|---|
|integer|Exit status|

`LaunchScript:`

Run a service script.

|Key|Type|Description|Required|Default|Min Version|
|---|---|---|---|---|---|
|path|string|Service script path|*|–|–|

No return value.

`OpenURL:`

Open a URL in a third-party app.

|Key|Type|Description|Required|Default|Min Version|
|---|---|---|---|---|---|
|url|string|URL to open|*|–|–|

No return value.

`ScanQRCode:`

Invoke camera to scan QR code.

No parameters.

|Return Type|Description|
|---|---|
|string|Scan result|

`SendMail:`

Compose and send an email in-app.

|Key|Type|Description|Required|Default|Min Version|
|---|---|---|---|---|---|
|subject|string|Subject|*|–|–|
|toRecipients|array of string|To recipients|*|–|–|
|ccRecipients|array of string|CC recipients|–|{}|–|
|bccRecipients|array of string|BCC recipients|–|{}|–|
|attachments|array of string|Attachment file paths|–|{}|–|

No return value.

`Null:`

No operation. Usually used to reset a specific preference and notify scripts. Requires XXT v1.2-10+.

No parameters, no return value.

## Example

```lua
{
    cell = "Button";
    action = "OpenURL:";
    label = "Contact info@xxtouch.app";
    args = {
        url = "mailto:info@xxtouch.app";
    }
};
```

![XUI-Button.png](XUIScreenshots/XUI-Button.png)

---

Source: [Location Picker](https://xxtouch.app/en/docs/XUI/Snippet/loc.md)
Path: XUI/Snippet/loc.md

# Location Picker

Provides a system map component allowing the user to drop a pin to select a geographic location.

Type `loc` returns a dictionary with latitude and longitude.

|Key|Type|Description|
|---|---|---|
|latitude|number|Latitude|
|longitude|number|Longitude|

## Example

```lua
local group, name

group = 'Utility'
name = 'loc = {latitude, longitude}'

return {
    name = string.format('%s - %s', group, name),
    description = "Location selection",
    arguments = {
        {type = 'loc', hint = 'Select a location'},
    },
    default = {
        latitude = 39.92,
        longitude = 116.46
    },
    generator = function(loc)
        return string.format('loc = {%f, %f}', loc.latitude, loc.longitude)
    end,
}
```

![IMG_0007.PNG](XUIScreenshots/IMG_0007.PNG)

---

Source: [APIs Available in XUI](https://xxtouch.app/en/docs/XUI/Internal_Lua_Module.md)
Path: XUI/Internal_Lua_Module.md

# APIs Available in XUI

`.xui` files are special Lua scripts with access to a limited set of service modules, mainly for checking device type, reloading the UI, and reading or writing configuration data. Only the APIs listed below are available in `.xui` scripts; any API not listed is unavailable in `.xui`.

## XPP and XUI Modules

- [XPP Script Bundle Module](/en/docs/handbook/xpp/index.md) `xpp`
- [XUI Script Configuration Interface Module](/en/docs/handbook/xui/index.md) `xui`

## Extended String Module (string)

- [Compare two version numbers](/en/docs/handbook/ext-string/string.compare_version.md) `string.compare_version`

## App Module (app)

- [Open a URL in foreground](/en/docs/handbook/app/app.open_url.md) `app.open_url`

## Screen Module (screen)

- [Get screen size](/en/docs/handbook/screen/screen.size.md) `screen.size`

## System Module (sys)

- [Get system version](/en/docs/handbook/sys/sys.version.md) `sys.version`
- [Get XXTouch version](/en/docs/handbook/sys/sys.xtversion.md) `sys.xtversion`

## Device Module (device)

- [Get device type](/en/docs/handbook/device/device.type.md) `device.type`
- [Get device name](/en/docs/handbook/device/device.name.md) `device.name`

## PLIST Module (plist)

- [Read plist file](/en/docs/handbook/plist/plist.read.md) `plist.read`
- [Write plist file](/en/docs/handbook/plist/plist.write.md) `plist.write`

## JSON Module (json)

- [Encode Lua value to JSON string](/en/docs/handbook/json/json.encode.md) `json.encode`
- [Decode JSON string to Lua value](/en/docs/handbook/json/json.decode.md) `json.decode`
- [JSON NULL constant](/en/docs/handbook/json/json.null.md) `json.null`

---

Source: [TextField](https://xxtouch.app/en/docs/XUI/Modules/TextField.md)
Path: XUI/Modules/TextField.md

# TextField

Displays a single-line text field for string input.

|Key|Type|Description|Required|Default|Min Version|
|---|---|---|---|---|---|
|alignment|string|Text alignment|–|Left|–|
|keyboard|string|Keyboard type|–|Default|–|
|placeholder|string|Placeholder text|Localizable|""|–|
|isSecure|boolean|Mask characters with dots|–|false|–|
|clearButtonMode|string|Show clear button|–|Never|–|
|maxLength|integer|Max text length|–|INT_MAX|–|
|validationRegex|string|Regex used to validate input|–|nil|1.2-10|
|prompt|string|Prompt title|Localizable|nil|1.2-10|
|message|string|Prompt message|Localizable|nil|1.2-10|
|okTitle|string|Prompt confirm button title|Localizable|"好"|1.2-10|
|cancelTitle|string|Prompt cancel button title|Localizable|"取消"|1.2-10|

This component does not support `icon`. If `title` is set, it is recommended to set `alignment` to "Right".

If the input fails to match `validationRegex`, it cannot be saved.

If either `prompt` or `message` is non-empty, tapping the TextField will show a prompt dialog requesting input there.

|alignment|Description|
|---|---|
|Left|Left|
|Center|Center|
|Right|Right|
|Natural|Natural|
|Justified|Justified|

|keyboard|Description|
|---|---|
|Default|System and third-party keyboards|
|Alphabet|ASCII|
|ASCIICapable|ASCII|
|NumbersAndPunctuation|Numbers and punctuation|
|URL|URL|
|NumberPad|Number pad|
|PhonePad|Phone pad|
|NamePhonePad|Name and phone|
|EmailAddress|Email address|
|DecimalPad|Number with decimal point|

|clearButtonMode|Description|
|---|---|
|Never|Never|
|Always|Always|
|WhileEditing|While editing|
|UnlessEditing|Unless editing|

|Return Type|Description|
|---|---|
|string|Text field value|

# Theme

|Theme Key|Type|Description|
|---|---|---|
|textColor|Color|Text color|
|caretColor|Color|Caret color|
|placeholderColor|Color|Placeholder color|

## Example

```lua
{
    default = "";
    label = "Username";
    cell = "TextField";
    key = "username";
    keyboard = "Default";
    alignment = "Right";
    placeholder = "Enter username";
    maxLength = 21;
    validationRegex = "^[0-9a-zA-Z]+$";
};
{
    isSecure = true;
    default = "";
    label = "Password";
    cell = "TextField";
    key = "password";
    keyboard = "NumberPad";
    alignment = "Right";
    placeholder = "Enter password";
    prompt = "Enter password";
    message = "Please input a 6-digit numeric password";
    validationRegex = "^[0-9]{6}$";
    okTitle = "Save";
    cancelTitle = "Cancel";
};
```

![XUI-TextField.png](XUIScreenshots/XUI-TextField.png)

![XUI-TextField-Prompt.png](XUIScreenshots/XUI-TextField-Prompt.png)

---

Source: [Image Position & Color Picker](https://xxtouch.app/en/docs/XUI/Snippet/poscolor.md)
Path: XUI/Snippet/poscolor.md

# Image Position & Color Picker

Provides pickers for choosing a screenshot from the system Camera Roll or the home directory, then selecting one or more pixels on it to obtain their positions and/or colors.

Type `pos` selects a single pixel and returns an array of two numbers: x and y.

```lua
{ 512, 373 }
```

Type `color` selects a single pixel and returns its color as a numeric RGB value:

```lua
0x3c1f8b
```

Type `poscolor` selects a single pixel and returns an array of three numbers: x, y, and numeric RGB color:

```lua
{ 512, 373, 0x3c1f8b }
```

Type `poscolors` selects one or more pixels and returns a 2D array: each entry contains x, y, and numeric RGB color:

```lua
{
    { 512, 373, 0x3c1f8b },
    { 512, 374, 0x3c1f7c },
    { 512, 375, 0x3c1f89 },
    -- ...
}
```

## Example

```lua
local group, name

group = 'Image/Color'
name = 'if (screen.is_colors(poscolors, 90)) then ... end'

return {
    name = string.format('%s - %s', group, name),
    description = "Multi-point color match on screen",
    arguments = {
        {type = 'poscolors'},
    },
    -- default = nil,
    generator = function(poscolors)
        local pcs = {}
        for i, pc in ipairs(poscolors) do
            pcs[#pcs + 1] = string.format('\t{ %4d, %4d, 0x%06x}, -- %3d\n', pc[1], pc[2], pc[3] & 0x00ffffff, i)
        end
        -- Insert @@ in the returned code so the editor cursor moves there automatically.
        return string.format([[
if (screen.is_colors({
%s}, 90)) then
    @@
end]], table.concat(pcs))
    end,
}
```

![IMG_0009.PNG](XUIScreenshots/IMG_0009.PNG)

![IMG_0010.PNG](XUIScreenshots/IMG_0010.PNG)

![IMG_0013.PNG](XUIScreenshots/IMG_0013.PNG)

---

Source: [Radio / Checkbox](https://xxtouch.app/en/docs/XUI/Modules/Radio_Checkbox.md)
Path: XUI/Modules/Radio_Checkbox.md

# Radio / Checkbox

Displays radio buttons or checkboxes.

Tapping a radio button selects it and deselects others in the same group.
Tapping a checkbox toggles its selection state.

|Key|Type|Description|Required|Default|Min Version|Notes|
|---|---|---|---|---|---|---|
|options|array of dictionaries|Options list|*|–|–|–|
|numPerLine|integer|Items per line|–|2 on iPhone, 4 on iPad|1.2-10|Max 12|
|minCount|integer|Minimum selected items|–|0|–|Checkbox only|
|maxCount|integer|Maximum selected items|–|INT_MAX|–|Checkbox only|

Each option dictionary has:

|Key|Type|Description|Condition|
|---|---|---|---|
|title|string|Option title|Localizable|
|value|primitive|Saved value; defaults to `title` if omitted|Optional|

This component does not support `label`/`icon`/`height`. Use `Group` to add titles/descriptions.

|Return Type|Description|
|---|---|
|array of primitive|Array of selected option values|

# Theme

|Theme Key|Type|Description|
|---|---|---|
|tagTextColor|Color|Tag text color|
|tagSelectedTextColor|Color|Selected tag text color|
|tagBackgroundColor|Color|Tag background color|
|tagSelectedBackgroundColor|Color|Selected tag background color|
|tagBorderColor|Color|Tag border color|
|tagSelectedBorderColor|Color|Selected tag border color|

## Example

```lua
{
    cell = "Group";
    label = "Checkbox Group";
    footerText = "Tap to select; tap again to deselect; up to 4 items";
};
{
    default = { "Red"; "Green"; };
    cell = "Checkbox";
    key = "checkbox";
    maxCount = 4;
    numPerLine = 4;
    options = {
        { title = "Red"; };
        { title = "Green"; };
        { title = "Blue"; };
        { title = "Yellow"; };
        "Purple";
        "Black";
        "White";
        "Brown";
        "Khaki";
        "Gray";
    };
};
{
    cell = "Group";
    label = "Radio Group";
    footerText = "Tap to select";
};
{
    default = "Fifth";
    cell = "Radio";
    key = "radio";
    options = {
        { title = "First"; };
        { title = "Second"; };
        { title = "Third"; };
        { title = "Fourth"; };
        { title = "Fifth"; value = "Fifth"; };
        "Last";
    };
};
```

![XUI-Radio.png](XUIScreenshots/XUI-Radio.png)

![XUI-Checkbox.png](XUIScreenshots/XUI-Checkbox.png)

---

Source: [Image Rect Picker](https://xxtouch.app/en/docs/XUI/Snippet/rect.md)
Path: XUI/Snippet/rect.md

# Image Rect Picker

Allows choosing a screenshot from the system Camera Roll or the home directory, then selecting a rectangular area on it.

Type `rect` returns an array of four numbers: x1, y1, x2, y2 for the top-left and bottom-right corners.

```lua
{ 0, 534, 295, 626 }
```

## Example

```lua
local group, name

group = 'Image/Color'
name = 'text = screen.ocr_text(rect)'

return {
    name = string.format('%s - %s', group, name),
    description = "OCR text in a screen region",
    arguments = {
        {type = 'rect'},
    },
    generator = function(rect)
        return string.format('text = screen.ocr_text(%d, %d, %d, %d)', rect[1], rect[2], rect[3], rect[4])
    end,
}
```

![IMG_0015.PNG](XUIScreenshots/IMG_0015.PNG)

---

Source: [Segment](https://xxtouch.app/en/docs/XUI/Modules/Segment.md)
Path: XUI/Modules/Segment.md

# Segment

Displays a segmented control for single selection (generally when the total number of options is fewer than 6).

|Key|Type|Description|Required|Default|Min Version|
|---|---|---|---|---|---|
|options|array of dictionaries|Options list|*|–|–|

Each option dictionary has:

|Key|Type|Description|Condition|
|---|---|---|---|
|title|string|Option title|Localizable|
|value|primitive|Saved value; defaults to `title` if omitted|Optional|

This component does not support `icon`.

|Return Type|Description|
|---|---|
|primitive|Selected option value|

## Example

```lua
{
    default = "Blue";
    label = "Segmented options";
    cell = "Segment";
    key = "list-segment";
    options = {
        { title = "Red"; };
        { title = "Blue"; };
        { title = "Gray"; };
        { title = "Yellow"; };
    };
};
```

![XUI-Segment.png](XUIScreenshots/XUI-Segment.png)

---

Source: [Option](https://xxtouch.app/en/docs/XUI/Modules/Option.md)
Path: XUI/Modules/Option.md

# Option

Displays a submenu entry linking to a list of options for single selection.

|Key|Type|Description|Required|Default|Min Version|
|---|---|---|---|---|---|
|options|array of dictionaries|Options list|*|–|–|
|footerText|string|Small text shown below the options|Localizable|""|–|
|popoverMode|boolean|Use popover style|–|false|1.2-4|

Each option dictionary has:

|Key|Type|Description|Condition|
|---|---|---|---|
|title|string|Option title|Localizable|
|value|primitive|Saved value; defaults to `title` if omitted|Optional|
|icon|string|Option icon path|Optional|
|shortTitle|string|Text displayed on the right side of the parent row|Optional, Localizable|

|Return Type|Description|
|---|---|
|primitive|Selected option value|

## Example

```lua
{
    default = "Green";
    label = "Single selection";
    cell = "Option";
    key = "list-1";
    options = {
        { title = "Red"; shortTitle = "Red"; };
        { title = "Green"; shortTitle = "Green"; };
        { title = "Blue"; shortTitle = "Blue"; };
    };
    popoverMode = false;
    -- footerText = "Select one";
};
```

![XUI-Option-1.png](XUIScreenshots/XUI-Option-1.png)

![XUI-Option-2.png](XUIScreenshots/XUI-Option-2.png)

---

Source: [MultipleOption](https://xxtouch.app/en/docs/XUI/Modules/MultipleOption.md)
Path: XUI/Modules/MultipleOption.md

# MultipleOption

Displays a submenu entry linking to a list of options that allows multiple selections.

|Key|Type|Description|Required|Default|Min Version|
|---|---|---|---|---|---|
|options|array of dictionaries|Options list|*|–|–|
|footerText|string|Small text shown below the options|Localizable|""|–|
|maxCount|integer|Max selected items|–|INT_MAX|–|
|popoverMode|boolean|Use popover style|–|false|1.2-4|

Each option dictionary has:

|Key|Type|Description|Condition|
|---|---|---|---|
|title|string|Option title|Localizable|
|value|primitive|Saved value; defaults to `title` if omitted|Optional|
|icon|string|Option icon path|Optional|

|Return Type|Description|
|---|---|
|array of primitive|Array of selected option values|

## Example

```lua
{
    default = {
        "Red";
        "Green";
    };
    label = "Multiple selection";
    cell = "MultipleOption";
    key = "list-2";
    maxCount = 2;
    options = {
        { title = "Red"; icon = "res/red.png"; };
        { title = "Green"; icon = "res/green.png"; };
        { title = "Blue"; icon = "res/blue.png"; };
    };
    popoverMode = false;
    footerText = "Select up to two";
};
```

![XUI-MultipleOption-1.png](XUIScreenshots/XUI-MultipleOption-1.png)

![XUI-MultipleOption-2.png](XUIScreenshots/XUI-MultipleOption-2.png)

---

Source: [OrderedOption](https://xxtouch.app/en/docs/XUI/Modules/OrderedOption.md)
Path: XUI/Modules/OrderedOption.md

# OrderedOption

Displays a submenu entry linking to a list of options that supports ordered multiple selections.

|Key|Type|Description|Required|Default|Min Version|
|---|---|---|---|---|---|
|options|array of dictionaries|Options list|*|–|–|
|footerText|string|Small text shown below the options|Localizable|""|–|
|popoverMode|boolean|Use popover style|–|false|1.2-4|
|minCount|integer|Minimum selected items|–|0|–|
|maxCount|integer|Maximum selected items|–|INT_MAX|–|

Each option dictionary has:

|Key|Type|Description|Condition|
|---|---|---|---|
|title|string|Option title|Localizable|
|value|primitive|Saved value; defaults to `title` if omitted|Optional|
|icon|string|Option icon path|Optional|

|Return Type|Description|
|---|---|
|array of primitive|Array of selected option values|

## Example

```lua
{
    default = { "Red"; };
    label = "Ordered options";
    cell = "OrderedOption";
    key = "list-3";
    maxCount = 2;
    minCount = 1;
    options = {
        { title = "Red"; icon = "res/red.png"; };
        { title = "Green"; icon = "res/green.png"; };
        { title = "Blue"; icon = "res/blue.png"; };
    };
    popoverMode = false;
    footerText = "Select at least 1, at most 2";
};
```

![XUI-OrderedOption-1.png](XUIScreenshots/XUI-OrderedOption-1.png)

![XUI-OrderedOption-2.png](XUIScreenshots/XUI-OrderedOption-2.png)

![XUI-OrderedOption-Popover.png](XUIScreenshots/XUI-OrderedOption-Popover.png)

---

Source: [EditableList](https://xxtouch.app/en/docs/XUI/Modules/EditableList.md)
Path: XUI/Modules/EditableList.md

# EditableList

Displays a submenu entry linking to an editable list of strings.

|Key|Type|Description|Required|Default|Min Version|
|---|---|---|---|---|---|
|footerText|string|Small text shown below the list|Localizable|""|–|
|itemFooterText|string|Small text shown on the add-new-item page|Localizable|""|–|
|maxCount|integer|Maximum number of items|–|INT_MAX|–|
|validationRegex|string|Regex used to validate string items|–|nil|1.2-10|

When modifying or adding a string item, if it fails to match `validationRegex`, it cannot be saved.

|Return Type|Description|
|---|---|
|array of strings|List contents|

# Theme

|Theme Key|Type|Description|
|---|---|---|
|textColor|Color|Text color|
|caretColor|Color|Caret color|
|placeholderColor|Color|Placeholder color|

## Example

```lua
{
    maxCount = 10;
    cell = "EditableList";
    label = "Editable List";
    key = "list-4";
    default = {
        "Default";
    };
    validationRegex = "^[0-9a-zA-Z]+$";
};
```

![XUI-EditableList-1.png](XUIScreenshots/XUI-EditableList-1.png)

![XUI-EditableList-2.png](XUIScreenshots/XUI-EditableList-2.png)

---

Source: [Slider](https://xxtouch.app/en/docs/XUI/Modules/Slider.md)
Path: XUI/Modules/Slider.md

# Slider

Displays a slider for selecting a floating-point value.

|Key|Type|Description|Required|Default|Min Version|
|---|---|---|---|---|---|
|min|number|Minimum value|–|0.0|–|
|max|number|Maximum value|–|1.0|–|
|step|number|Step interval; slider snaps to nearest step|–|0|1.2-10|
|showValue|boolean|Show current value|–|false|–|

This component does not support `label`/`icon`. Use `Group` to add headings/descriptions.

|Return Type|Description|
|---|---|
|number|Slider value|

# Theme

|Theme Key|Type|Description|
|---|---|---|
|tintColor|Color|Track tint color|
|thumbColor|Color|Thumb color|

## Example

```lua
{
    showValue = true;
    min = 1;
    default = 5;
    max = 10;
    step = 0.5;
    label = "Slider";
    cell = "Slider";
    key = "slider";
};
```

![XUI-Slider.png](XUIScreenshots/XUI-Slider.png)

---

Source: [Stepper](https://xxtouch.app/en/docs/XUI/Modules/Stepper.md)
Path: XUI/Modules/Stepper.md

# Stepper

Displays an increment/decrement stepper for numeric values.

|Key|Type|Description|Required|Default|Min Version|
|---|---|---|---|---|---|
|min|number|Minimum value|–|1|–|
|max|number|Maximum value|–|100|–|
|step|number|Step interval|–|1|–|
|isInteger|boolean|Display as integer|–|false|–|
|autoRepeat|boolean|Long-press repeats|–|true|–|

This component does not support `icon`.

|Return Type|Description|
|---|---|
|number|Current value|

## Example

```lua
{
    min = 1;
    default = 25;
    max = 100;
    autoRepeat = true;  -- Long-press auto repeat
    label = "Stepper";
    cell = "Stepper";
    key = "stepper";
    isInteger = true;  -- Display as integer
};
```

![XUI-Stepper.png](XUIScreenshots/XUI-Stepper.png)

---

Source: [DateTime](https://xxtouch.app/en/docs/XUI/Modules/DateTime.md)
Path: XUI/Modules/DateTime.md

# DateTime

Displays a date/time picker for selecting date, time, or an interval.

|Key|Type|Description|Required|Default|Min Version|
|---|---|---|---|---|---|
|min|number|Minimum interval|–|0|–|
|max|number|Maximum interval|–|FLOAT_MAX|–|
|minuteInterval|integer|Step in minutes|–|1|–|
|mode|string|Picker mode|–|datetime|–|
|format|string|Time format (ISO8601)|–|nil|–|

This component does not support `label`/`icon`. Use `Group` to add headings/descriptions.

|mode|Description|
|---|---|
|datetime|Date & time picker|
|date|Date picker|
|time|Time picker|
|interval|Time interval picker|

|Return Type|Condition|Description|
|---|---|---|
|integer|`format == nil`|Unix timestamp or seconds for interval|
|string|`#format > 0`|Formatted string per `format`|

For date and time format patterns, see [Unicode: Date Format Patterns](https://www.unicode.org/reports/tr35/tr35-31/tr35-dates.html#Date_Format_Patterns).

## Example

```lua
{
    cell = "DateTime";
    key = "datetime1";
};
```

![XUI-DateTime.png](XUIScreenshots/XUI-DateTime.png)

---

Source: [TitleValue](https://xxtouch.app/en/docs/XUI/Modules/TitleValue.md)
Path: XUI/Modules/TitleValue.md

# TitleValue

Displays a key-value pair, like `Settings -→ General -→ About`.

|Key|Type|Description|Required|Default|Min Version|
|---|---|---|---|---|---|
|value|primitive|Value displayed on the right|–|nil|–|
|snippet|string|Snippet template filename|–|nil|–|

Swipe left to clear the saved value in preferences (does not override the `value` provided in the XUI config).

If both `defaults` and `key` are set for this component, it can display the actual value stored. If `snippet` is set to a `.snippet` template, the component gains a built-in snippet picker: tapping it launches the snippet picker queue and, upon completion, saves the result into this component's preference key. See [Snippet](/en/docs/XUI/Snippet/index.md).

## Example

```lua
{
    cell = "Group";
    label = "QR Code";
    footerText = "The scan result will appear in the field below";
};
{
    cell = "Button";
    label = "Open QR Scanner";
    key = "qr1";
    action = "ScanQRCode:";
    args = {};
};
{
    cell = "TitleValue";
    label = "Scan result";
    key = "qr1";
};
```

![XUI-TitleValue-QR.png](XUIScreenshots/XUI-TitleValue-QR.png)

![XUI-TitleValue-Snippets.png](XUIScreenshots/XUI-TitleValue-Snippets.png)

---

Source: [StaticText](https://xxtouch.app/en/docs/XUI/Modules/StaticText.md)
Path: XUI/Modules/StaticText.md

# StaticText

Displays static text, i.e., the text given in `label`.

|Key|Type|Description|Required|Default|Min Version|
|---|---|---|---|---|---|
|label|string|Displayed text|*|–|–|
|alignment|string|Text alignment|–|Left|–|
|selectable|boolean|Allow selecting/copying text|–|false|–|

|alignment|Description|
|---|---|
|Left|Left|
|Center|Center|
|Right|Right|
|Natural|Natural|
|Justified|Justified|

This component does not support `icon`, `height`, custom fonts, or custom sizes.

## Example

```lua
{
    cell = "Group";
    label = "Static text";
};
{
    cell = "StaticText";
    label = "This is static text";
};
{
    cell = "StaticText";
    label = "This static text is selectable";
    selectable = true;
};
```

![XUI-StaticText.png](XUIScreenshots/XUI-StaticText.png)

---

Source: [Textarea](https://xxtouch.app/en/docs/XUI/Modules/Textarea.md)
Path: XUI/Modules/Textarea.md

# Textarea

Displays a submenu entry linking to a multi-line text input page.

|Key|Type|Description|Required|Default|Min Version|
|---|---|---|---|---|---|
|maxLength|integer|Max text length|–|INT_MAX|–|
|keyboard|string|Keyboard type|–|Default|–|
|autoCapitalization|string|Auto-capitalization|–|None|–|
|autoCorrection|string|Auto-correction|–|Default|–|

|keyboard|Description|
|---|---|
|Default|System and third-party keyboards|
|Alphabet|ASCII|
|ASCIICapable|ASCII|
|NumbersAndPunctuation|Numbers and punctuation|
|URL|URL|
|NumberPad|Number pad|
|PhonePad|Phone pad|
|NamePhonePad|Name and phone|
|EmailAddress|Email address|
|DecimalPad|Number with decimal point|

|autoCapitalization|Description|
|---|---|
|None|None|
|Sentences|By sentence|
|Words|By word|
|AllCharacters|All characters|

|autoCorrection|Description|
|---|---|
|Default|Default|
|No|Off|
|Yes|On|

Custom fonts and sizes are not currently supported.

|Return Type|Description|
|---|---|
|string|Text content|

# Theme

|Theme Key|Type|Description|
|---|---|---|
|textColor|Color|Text color|
|caretColor|Color|Caret color|
|placeholderColor|Color|Placeholder color|

## Example

```lua
{
    default = "You can enter any text here...";
    cell = "Textarea";
    key = "textarea";
    label = "A text area";
};
```

![XUI-Textarea-1.png](XUIScreenshots/XUI-Textarea-1.png)

![XUI-Textarea-2.png](XUIScreenshots/XUI-Textarea-2.png)

---

Source: [Image / AnimatedImage](https://xxtouch.app/en/docs/XUI/Modules/Image_AnimatedImage.md)
Path: XUI/Modules/Image_AnimatedImage.md

# Image / AnimatedImage

Displays an image.

`Image` supports local static images (e.g., `.png`, `.jpg`). `AnimatedImage` supports `.gif`.

|Key|Type|Description|Required|Default|Min Version|
|---|---|---|---|---|---|
|path|string|Local image filename, or an online image URL|*|–|–|

This component must set the common property `height` to define the image height; the width adapts automatically while preserving the aspect ratio.

In XXTouch v1.2-11+, `AnimatedImage` also supports loading online static or animated images and caches them after loading. Provide an HTTP/HTTPS URL in `path`.

## Example

```lua
{
    cell = "Image";
    path = "res/bd_logo1_31bdc765.png";
    height = 128.0;
};
{
    cell = "AnimatedImage";
    path = "https://www.baidu.com/img/540%20258_c622d80176946df7f7b8d1997edf57d4.gif";
    height = 128.0;
};
```

![XUI-Image.png](XUIScreenshots/XUI-Image.png)

---

Source: [File](https://xxtouch.app/en/docs/XUI/Modules/File.md)
Path: XUI/Modules/File.md

# File

Displays a file picker row showing a file type icon, name, and modification time. Tap it to choose a new file. This is typically used to select a data file whose path is consumed by a service script.

|Key|Type|Description|Required|Default|Min Version|
|---|---|---|---|---|---|
|initialPath|string|Initial top-level directory|–|XPP root|–|
|allowedExtensions|array of string|Allowed file extensions|–|[]|–|
|label|string|Title shown when no file is selected|Localizable|""|1.2-10|
|footerText|string|Description shown when no file is selected|Localizable|""|1.2-10|
|isFile|boolean|Pick file if true; pick directory if false|–|true|1.2-10|

Swipe left to reveal a delete button to clear the saved value.

`initialPath` is relative to the XPP bundle. If omitted, the current XPP path is used.

`allowedExtensions` filters the displayed items; non-matching extensions are hidden and cannot be selected.

|Return Type|Description|
|---|---|
|string|Absolute path of the selected file|

# Theme

|Theme Key|Type|Description|
|---|---|---|
|labelColor|Color|Filename color|
|valueColor|Color|File description color|

## Example

```lua
{
    cell = "File";
    key = "file1";
    initialPath = "scripts";
    isFile = true;  -- Pick a file
    label = "Please choose a script";  -- Title
    -- footerText = "All script formats supported by XXT are allowed";
    allowedExtensions = { "lua"; "xxt"; "xpp" };  -- Allowed extensions
};
```

![XUI-File.png](XUIScreenshots/XUI-File.png)

---

Source: [About](https://xxtouch.app/en/docs/XUI/Modules/About.md)
Path: XUI/Modules/About.md

# About

Displays an "About" section.

|Key|Type|Description|Required|Default|Min Version|
|---|---|---|---|---|---|
|icon|string|Relative path of the About icon|–|""|–|

This component requires the common properties `label` and `value`, which are shown as the title and subtitle.

# Theme

|Theme Key|Type|Description|
|---|---|---|
|tintColor|Color|Title color|
|labelColor|Color|Subtitle color|

## Example

```lua
{
    cell = "About";
    imagePath = "res/xxt-icon.png";  -- Center icon
    label = "XUI Demo\nv1.2-10";  -- Title
    value = "For XXTouch v1.2-10 and later. Demo only; do not use in production.\n2016-2018 (c) XXTouch Team.\nAll Rights Reserved.";  -- Subtitle
};
```

![XUI-About.png](XUIScreenshots/XUI-About.png)

---

Source: [General Properties](https://xxtouch.app/en/docs/XUI/Creation/General.md)
Path: XUI/Creation/General.md

# General Properties

All components can use the following common properties to add titles, icons, specify where to store settings, etc. Some properties may behave slightly differently per component.

|Key|Type|Description|Condition|
|---|---|---|---|
|cell|string|Component type|–|
|label|string|Display label|Optional, localizable|
|defaults|string|Preferences domain identifier (the name of the settings file/section)|–|
|key|string|Preference key|`defaults != nil`|
|default|string|Default value|–|
|value|primitive|Current value|Optional|
|icon|string|Icon file name|Optional|
|readonly|boolean|Whether the component is read-only|Optional|
|height|number|Row height|Optional|

`cell` is the component type, such as `Button`, `Switch`, `Link`, etc.

`label` is the title, usually displayed on the left.

`default` is the default value. If `value` is `nil`, the `default` will be used to populate `value`.

`icon` is the icon shown to the left of `label`. If set to `res/16.png`, you are recommended to also provide `res/16@2x.png` and `res/16@3x.png`, whose actual pixel sizes should be 2x and 3x respectively.

If `readonly` is `true`, the component's value is read-only. It cannot be modified, cleared, or linked to a sub-page.

---

Source: [Read Settings](https://xxtouch.app/en/docs/XUI/Creation/ReadSettings.md)
Path: XUI/Creation/ReadSettings.md

# Read Settings

After configuration is saved to the location specified by `defaults`, read the value of key `key == "switch-1"` from the plist to get the state of switch "switch-1". For reading, writing, and updating XUI configuration, see the [XUI script configuration interface module](/en/docs/handbook/xui/index.md).

```lua
local switch1 = xui.get("com.yourcompany.A-Script-Bundle", "switch-1")
if (switch1) then
    -- ...
end
```

---

Source: [Root](https://xxtouch.app/en/docs/XUI/Creation/Root.md)
Path: XUI/Creation/Root.md

# Root

The root (top-level) of an XUI configuration is a dictionary.

|Key|Type|Description|Condition|
|---|---|---|---|
|title|string|Navigation bar title|Optional, localizable|
|header|string|Main header|Optional, localizable|
|subheader|string|Sub header|Optional, localizable|
|defaults|string|Preferences domain identifier (global settings file name)|–|
|items|array of dictionaries|Component list|–|
|theme|dictionary|Theme settings for the page|Optional|
|stringsTable|string|Localization table name, default `Localizable`|Optional|

`defaults` is the preferences domain identifier that specifies where settings are stored. For example, if `defaults` is `com.yourcompany.A-Script-Bundle`, the XUI settings will be saved to `uicfg/com.yourcompany.A-Script-Bundle.plist`. Individual components can also override `defaults`.

`items` is the array of component dictionaries to display in order. See [General Properties](/en/docs/XUI/Creation/General.md) for the definition of a component dictionary.

`stringsTable` is used only when you enable localization; properties marked as localizable will be resolved through the iOS-style strings table.

```lua
return {
    title = "A Script Bundle";
    header = "Configuration Demo";
    subheader = "An elegant configuration UI provided by XXTouch";
    defaults = "com.yourcompany.A-Script-Bundle";  -- Where settings are stored
    theme = {
        style = "Grouped";  -- Use "Plain" for plain list style
    };
    items = {
        {

        };  -- Component 1
        {

        };  -- Component 2
        {

        };  -- Component 3
    };
};
```

---

Source: [Theme](https://xxtouch.app/en/docs/XUI/Creation/Theme.md)
Path: XUI/Creation/Theme.md

# Theme

Set a `theme` dictionary at the root level to configure unified styles for the page. All components and sub-pages inherit every field from the root `theme` dictionary.

If you need to style a component individually, set a `theme` dictionary inside that component. Fields inside a component-level `theme` override the same keys from the root `theme` during a merge. Different components may have their own theme keys; see each component’s Theme table.

If a component links to a non-XUI sub-page (e.g. `Option`/`MultipleOption`/`OrderedOption`/`EditableList`), the sub-page uses the component’s `theme`. If a component links to another XUI sub-page (e.g. `Link`), the sub-page can set its own `theme`, which will be merged with its parent page’s theme.

![XUI-Dark.png](Theme/XUI-Dark.png)

# Page

|Key|Type|Description|
|---|---|---|
|style|Style|Page style|
|tintColor|Color|Foreground color|
|backgroundColor|Color|Background color|
|separatorColor|Color|Separator color between cells|
|backgroundImage|string|Relative path to background image|

# Navigation Bar

|Key|Type|Description|
|---|---|---|
|navigationBarColor|Color|Navigation bar background color|
|navigationTitleColor|Color|Navigation title color|

# Header & Footer

|Key|Type|Description|
|---|---|---|
|headerTextColor|Color|`header` text color|
|subheaderTextColor|Color|`subheader` text color|
|footerTextColor|Color|Footer text color|
|headerBackgroundColor|Color|`header` background color|
|footerBackgroundColor|Color|Footer background color|

# Common Cells

|Key|Type|Description|
|---|---|---|
|cellBackgroundColor|Color|Cell background color|
|disclosureIndicatorColor|Color|Disclosure indicator color|
|selectedColor|Color|Selected color|
|highlightedColor|Color|Highlighted color|
|labelColor|Color|Title text color|
|valueColor|Color|Value text color|

# Status

|Key|Type|Description|
|---|---|---|
|dangerColor|Color|Error color|
|warningColor|Color|Warning color|
|successColor|Color|Success color|

# Styles

|style|Description|
|---|---|
|Grouped|Grouped style (default)|
|Plain|Plain list style|

The `Color` type is a hex RGB/RGBA string beginning with `#`, e.g. `#FF0000` is red.

---

Source: [URL Scheme & QR Protocol](https://xxtouch.app/en/docs/URLScheme/index.md)
Path: URLScheme/README.md

# URL Scheme & QR Protocol

This protocol defines the actions and parameters supported by the XXTouch app's URL scheme.

Any of the following methods can wake XXTouch and trigger the corresponding behavior:

- Open URLs of the form `xxt://`
- Scan QR codes containing `xxt://` URLs
- Scan QR codes containing an action and parameter dictionary

---

- [Open Scanner](Scan.md)
- [Run Script](Launch.md)
- [Stop Script](Stop.md)
- [Bind License](License.md)
- [XUI](XUI.md)
- [Downloads](Download.md)
- [Restore Workspace](Workspace.md)

---

Source: [Open Scanner](https://xxtouch.app/en/docs/URLScheme/Scan.md)
Path: URLScheme/Scan.md

# Open Scanner

```
xxt://scan/
```

Open the built-in scanner.

- QR dictionary

```json
{
    "event":"scan"
}
```

---

Source: [Run Script](https://xxtouch.app/en/docs/URLScheme/Launch.md)
Path: URLScheme/Launch.md

# Run Script

```
xxt://launch/
```
```
xxt://launch/?path=%@
```

`path` is the absolute path of the script to run. If `path` is not specified, the currently selected script will be launched.

- QR dictionary

```json
{
    "event":"launch",
    "path":"[absolute path of the script to run]"
}
```

---

Source: [Stop Script](https://xxtouch.app/en/docs/URLScheme/Stop.md)
Path: URLScheme/Stop.md

# Stop Script

```
xxt://stop/
```

Stop the currently running script.

- QR dictionary

```json
{
    "event":"stop"
}
```

---

Source: [Bind License](https://xxtouch.app/en/docs/URLScheme/License.md)
Path: URLScheme/License.md

# Bind License

```
xxt://license/
```
```
xxt://license/?code=%@
```

Open the license screen and prefill the license code. `code` is a 12- or 16-character license string.

- QR dictionary

```json
{
    "event":"license",
    "code":"[license code text]"
}
```

---

Source: [XUI](https://xxtouch.app/en/docs/URLScheme/XUI.md)
Path: URLScheme/XUI.md

# XUI

```
xxt://xui/?bundle=%@&name=%@
```

Configure a script bundle and open a specific XUI file inside it. `bundle` is the absolute path to the script bundle, and `name` is the relative path of the XUI file within the bundle.

- QR dictionary

```json
{
    "event":"xui",
    "bundle":"[absolute path to script bundle]",
    "name":"[relative path of XUI file within the bundle]"
}
```

---

Source: [Downloads](https://xxtouch.app/en/docs/URLScheme/Download.md)
Path: URLScheme/Download.md

# Downloads

```
xxt://download/?path=%@&url=%@
```

Download a file from the specified URL. `path` is the saved filename, and `url` is the download URL.

- Notes
    - If `path` is not specified, the filename will be inferred from the target URL, or the last path component of the URL will be used.
    - `path` can be absolute or relative. If relative, it is relative to the current directory in the app's file browser.

- QR dictionary

```json
{
    "event":"download",
    "path":"[filename-to-save.lua]",
    "url":"[download-url]"
}
```

---

Source: [Restore Workspace](https://xxtouch.app/en/docs/URLScheme/Workspace.md)
Path: URLScheme/Workspace.md

# Restore Workspace

```
xxt://workspace/
```

Restore the XXTouch app to its initial state and close all open pages.

- QR dictionary

```json
{
    "event":"workspace"
}
```

---

Source: [FAQ Index](https://xxtouch.app/en/docs/FAQ/index.md)
Path: FAQ/README.md

# FAQ Index

---

- [What is XXTouch?](faq-0001.md)
- [Which devices can run XXTouch?](faq-0002.md)
- [How do I install XXTouch on a device?](faq-0003.md)
- [Is XXTouch paid? Which features require payment?](faq-0004.md)
- [What rights do I get after purchasing a license?](faq-0005.md)
- [What are the limitations without a license?](faq-0006.md)
- [How do I import a script from my computer via USB?](faq-0007.md)
- [Rootless vs traditional jailbreak: pros and cons](faq-0008.md)
- [Where are scripts and related assets stored on device?](faq-0009.md)
- [How do I develop scripts on a computer?](faq-0010.md)
- [As a developer, how can I charge for my script?](faq-0011.md)
- [Cydia shows “This server’s certificate is invalid.” when adding source](faq-0012.md)
- [Install/update fails in Cydia (red/yellow text)](faq-0013.md)
- [Cannot add XXTouch source in Cydia](faq-0014.md)
- [No packages found in XXTouch source in Cydia](faq-0015.md)
- [App crashes after install or no icon or cannot tap to open](faq-0016.md)
- [Endless sync failure prompts after install](faq-0017.md)
- [Endless prompts to respring / communication failed?](faq-0018.md)
- [Limitations of rootless/roothide/TrollStore editions](faq-0019.md)
- [License appears invalid before expiry?](faq-0020.md)
- [What is special about the roothide environment?](faq-0021.md)
- [Where to adjust iOS date and time?](faq-0022.md)
- [Picker/Editor/LAN controller can’t find device](faq-0023.md)
- [Why “Frame loading failed” when scanning to download?](faq-0024.md)
- [How to record scripts?](faq-0025.md)
- [How to run scripts?](faq-0026.md)
- [How to select the script to run?](faq-0027.md)
- [How to edit scripts on device?](faq-0028.md)
- [How to encrypt scripts?](faq-0029.md)
- [What can scripts do?](faq-0030.md)
- [Can encrypted scripts be decrypted?](faq-0031.md)
- [Can XXTouch run on a computer?](faq-0032.md)
- [Can XXTouch run on Android?](faq-0033.md)
- [How do I install TrollStore on a device?](faq-0034.md)

---

Source: [What is XXTouch?](https://xxtouch.app/en/docs/FAQ/faq-0001.md)
Path: FAQ/faq-0001.md

# What is XXTouch?

XXTouch is an automation tool for jailbroken iOS environments.
Developers write Lua scripts that XXTouch executes to automate various tasks. XXTouch itself does not bundle any ready-made scripts, nor does it auto-generate scripts for any specific scenario.

To write your own scripts, refer to:
- [XXTouch iOS Developer Handbook](/en/docs/handbook/index.md)
- [Lua 5.3 Reference Manual](https://www.lua.org/manual/5.3/manual.html)

---

Source: [Which devices can run XXTouch?](https://xxtouch.app/en/docs/FAQ/faq-0002.md)
Path: FAQ/faq-0002.md

# Which devices can run XXTouch?

---

## iOS 9.0 and Later Devices That Support Jailbreaking or TrollStore

XXTouch does not support XinA jailbreak. If you used it, please re-jailbreak with [Dopamine](https://ellekit.space/dopamine/) or [palera1n](https://palera.in/).

These support ranges were checked on November 5, 2026. The iOS version ranges also apply to the corresponding iPadOS versions. Available versions also depend on which system versions the device can run; check each tool’s device compatibility list as well.

### TrollStore supported

[TrollStore](https://ios.cfw.guide/installing-trollstore/) supports iOS 14.0 to 16.6.1, 16.7 RC (20H18), 17.0.0.

### Supported rootless jailbreaks

[Dopamine 3.x](https://ellekit.space/dopamine/) supports the following:

| Chip | iOS / iPadOS version |
| --- | --- |
| A8 to A11 (arm64) | 15.0 to 18.7.1 |
| A12 / A13 | 15.0 to 18.7.1, 26.0 to 26.0.1 |
| A14 to A16 / M1 to M2 | 15.0 to 17.3.1 |
| A17 Pro | 17.0 to 17.3.1 |

[palera1n](https://palera.in/) supports iOS 15.0 and later, only on A8 to A11 devices.

### Supported roothide jailbreaks

[Bootstrap](https://github.com/roothide/Bootstrap) supports iOS 15.0 to 16.6.1, 16.7 RC (20H18), 17.0.0.

[Dopamine-Roothide 3.x](https://github.com/roothide/Dopamine-roothide) supports the same chips and system versions as Dopamine 3.x in the table above.

[Relaxin](https://relaxin.owngoal.dev/) is a roothide jailbreak currently in public beta. v0.5.7 supports the following:

| Chip | iOS / iPadOS version |
| --- | --- |
| A10 / A10X | 16.1 to 18.7.1 |
| A11 | 16.1 to 16.7.16 |
| A12 / A13 | 16.1 to 18.7.1, 26.0 to 26.0.1 |
| A14 to A16 / M1 to M2 | 16.1 to 17.3.1 |
| A17 Pro | 17.0 to 17.3.1 |

Support for iOS / iPadOS 16.1 to 16.4.1 is experimental.

### Supported traditional (rootful) jailbreaks

[palera1n](https://palera.in/) supports iOS 15.0 and later, only on A8 to A11 devices.
[checkra1n](https://checkra.in/) supports iOS 12.0 to 14.8.1, only on A7 to A11 devices.
[Taurine](https://taurine.app/) supports iOS 14.0 to 14.8.1.
[unc0ver](https://ios.cfw.guide/installing-unc0ver/) supports iOS 11.0 to 14.8.
[Electra](https://ios.cfw.guide/installing-electra/) supports iOS 11.0 to 11.4.1.
[doubleH3lix](https://ios.cfw.guide/installing-doubleh3lix-ipa/) supports iOS 10.0 to 10.3.3, only on A7 to A9 devices.
[pangu933](https://ios.cfw.guide/installing-pangu933/) supports iOS 9.2 to 9.3.3.
[pangu9](https://ios.cfw.guide/installing-pangu9/) supports iOS 9.0 to 9.0.2.

---

Source: [How do I install XXTouch on a device?](https://xxtouch.app/en/docs/FAQ/faq-0003.md)
Path: FAQ/faq-0003.md

# How do I install XXTouch on a device?

Before installing, make sure your device meets the following requirements:
- It is an iOS device
- It is either **jailbroken** or has **TrollStore** installed

Need help? See:
- [How to jailbreak an iOS device](https://ios.cfw.guide/)
- [How to install TrollStore](./faq-0034.md)

---

## Install in a jailbroken environment

After jailbreaking, add the source [https://xxtouch.app/](https://xxtouch.app/) in Cydia or Sileo, then install XXTouch.

---

## Install via TrollStore

Before installing, please uninstall the jailbreak edition of XXTouch from Sileo or Cydia.

### Online installation

- On the device, open [https://xxtouch.app/](https://xxtouch.app/) in `Safari`
- Long press `TIPA for TrollStore` → Copy Link
- Open `TrollStore` → tap `+` in the top-right corner → `Install from URL` → paste the link → `Install`

### Offline installation

- On your computer, open [https://xxtouch.app/](https://xxtouch.app/) and download `TIPA for TrollStore`
- **macOS:** AirDrop the downloaded `.tipa` to the device with TrollStore installed, then approve the installation
- **Windows:**
    1. Install `ES File Explorer` on the device
    2. Use i4Tools to copy the `.tipa` into ES File Explorer's Documents folder
    3. On the device, open `Files` → `On My iPhone/iPad` → locate `ES File Explorer Documents`
    4. Share the file and open it in `TrollStore`

---

Source: [Is XXTouch paid? Which features require payment?](https://xxtouch.app/en/docs/FAQ/faq-0004.md)
Path: FAQ/faq-0004.md

# Is XXTouch paid? Which features require payment?

---

## Is XXTouch paid?

Yes. XXTouch is paid software.

## Which features require payment?

Running scripts requires a paid license.

## Reference pricing

```
Monthly (31 days) license code:  40 CNY per device
Yearly  (366 days) license code: 100 CNY per device
```

## Purchase notes

Your license code is your only proof of purchase. It is not tied to any identity, and lost codes **cannot** be reissued, so keep it safe.

The license fee covers only the right to use the XXTouch application itself. It does not include custom script development, training, or social privileges in forums, QQ groups, or other communities.
**Before purchasing a license code, please make sure you understand your [rights](faq-0005.md) and the [restrictions](faq-0006.md) that will be lifted after purchase.**

## How to purchase

Online store (automated): [http://vip1.lat/L1PF](http://vip1.lat/L1PF)

## [How to use a license code?](/en/docs/ABC/index.md#how-to-activate-license)

---

Source: [What rights do I get after purchasing a license?](https://xxtouch.app/en/docs/FAQ/faq-0005.md)
Path: FAQ/faq-0005.md

# What rights do I get after purchasing a license?

## About license codes and trial period

A single license code can activate XXTouch on **one** device at a time (the device must have XXTouch installed and running).
Every device gets a one-time **168-hour** full-featured trial — we recommend making full use of the trial to confirm XXTouch meets your needs before purchasing.

## License transfer policy

| License type | Unbind allowance |
| --- | --- |
| Monthly (retail) | 2 times |
| Yearly (retail) | 8 times |

- A license cannot be unbound within 24 hours of binding.
- A license cannot be transferred from a device with fewer than 7 days of remaining time.

## License validity notes

Replacing the battery, reinstalling the app, updating the app, or re-jailbreaking will **not** affect the device's license status.

---

Source: [What are the limitations without a license?](https://xxtouch.app/en/docs/FAQ/faq-0006.md)
Path: FAQ/faq-0006.md

# What are the limitations without a license?

## Limitations

- Without a license, XXTouch limits each script run to 5 minutes.
- Unlicensed devices cannot encrypt scripts.

## Trial period

Each device can receive a one-time **168-hour** full-featured trial.
The trial begins automatically the first time you attempt to run a script.
There are no feature restrictions during the trial; functionally, it is the same as a paid license.

## Features not restricted by license

The following features are available without a license:
- Remote Interface (e.g., remote screenshots, remote file access)
- On-device code editor
- Color picker (on device or desktop)

---

Source: [How do I import a script from my computer via USB?](https://xxtouch.app/en/docs/FAQ/faq-0007.md)
Path: FAQ/faq-0007.md

# How do I import a script from my computer via USB?

Use iTools (or any desktop tool that can browse iOS file systems) to copy the script file to the following directory on the device:
```bash
<user system>/1ferver/lua/scripts/
```

:::note
`<user system>` refers to the display name of the device's user filesystem in iTools. Different tools may show different names, such as *User System* or *File System (User)*.
:::

---

Source: [Rootless vs traditional (rootful) jailbreak: pros and cons](https://xxtouch.app/en/docs/FAQ/faq-0008.md)
Path: FAQ/faq-0008.md

# Rootless vs traditional (rootful) jailbreak: pros and cons

## Advantages

- System files are read-only, preventing accidental deletion of critical system files.
- You can use "Erase All Content and Settings" to wipe the device without any extra preparation.

## Disadvantages

- System files are read-only, so packages made for traditional jailbreaks are not compatible.

---

Source: [Where are scripts and resources stored on the device?](https://xxtouch.app/en/docs/FAQ/faq-0009.md)
Path: FAQ/faq-0009.md

# Where are scripts and resources stored on the device?

| Category | Path |
| --- | --- |
| Scripts | `/var/mobile/Media/1ferver/lua/scripts/` |
| Plugins | `/var/mobile/Media/1ferver/lib/` |
| Resources | `/var/mobile/Media/1ferver/res/` |
| Logs | `/var/mobile/Media/1ferver/log/` |
| Tesseract OCR data | `/var/mobile/Media/1ferver/tessdata/` |
| OCR inference models | `/var/mobile/Media/1ferver/models/` |
| Built-in script modules | `/var/mobile/Media/1ferver/lua/` |

:::tip
On rootless jailbreaks, you may need [`jbroot`](/en/docs/handbook/develop-helper/jbroot.md) to access these paths.
:::

---

Source: [How do I develop XXTouch scripts on a computer?](https://xxtouch.app/en/docs/FAQ/faq-0010.md)
Path: FAQ/faq-0010.md

# How do I develop XXTouch scripts on a computer?

1. [Download development tools](/en/docs/handbook/supplement/dev-tools.md)
2. [Read the developer handbook](/en/docs/handbook/index.md)

---

Source: [As a developer, how can I charge for my script?](https://xxtouch.app/en/docs/FAQ/faq-0011.md)
Path: FAQ/faq-0011.md

# As a developer, how can I charge for my script?

XXTouch currently has no official resale or license verification platform.

## Possible approaches

- Deploy your own license verification service
- Implement licensing and access control directly within your script
- Integrate a third-party license verification platform

---

Source: [“This server’s certificate is invalid.” when adding XXTouch source in Cydia](https://xxtouch.app/en/docs/FAQ/faq-0012.md)
Path: FAQ/faq-0012.md

# “This server’s certificate is invalid.” when adding XXTouch source in Cydia

First, confirm the official source URL:
- [**xxtouch.app**](https://xxtouch.app)

Then check the following:
- Disable any network proxy or VPN on the device
- Ensure the device has a working internet connection
- Verify that the device date, time, and time zone are correct
  - Go to **Settings → General → Date & Time** and [adjust manually](faq-0022.md) if needed

---

Source: [Install/update fails in Cydia (red/yellow text)](https://xxtouch.app/en/docs/FAQ/faq-0013.md)
Path: FAQ/faq-0013.md

# Install/update fails in Cydia (red/yellow text)

## Fix red errors caused by insufficient system partition space

If the red text contains any of the following:
**No space left on device**
**cannot copy extracted data for**
**failed in buffer_write(fd) (8, ret=-1)**
Your system partition may be out of space.
Try uninstalling unnecessary tweaks or removing useless resources.
Do NOT delete `/.cydia_no_stash` to free space, or the device will enter a bootloop!

## Possible fix for iOS 9.2 ~ 10.2.1 (not 9.3.5)

1. Connect to power and keep it charged. Remove all sources except Cydia/Telesphoreo and XXTouch (this will not cause any data loss).
   - Tap “Sources” → top-right “Edit” → tap the red minus icon in front of a source
2. Add the source `apt.abcydia.com` (Leifeng repo)
3. In Cydia choose to uninstall `Cydia Substrate` and take a screenshot of the uninstall list. Do NOT confirm yet. Read the next lines carefully:
   - This will also uninstall many tweaks including XXTouch. In theory this is safe, but we cannot assume responsibility. If you have concerns, stop here and consult a trusted professional.
   - After understanding the above, decide whether to confirm uninstall.
4. Search for and install the tweak "Stashing 容量不足修正"
5. Space should now be sufficient. If needed, reinstall what was removed in step 3.

## Possible fix for iOS 9.3.5 jailbroken via Phœnix

1. Connect to power and keep it charged. Remove all sources except Cydia/Telesphoreo and XXTouch (this will not cause any data loss).
   - Tap "Sources" → top-right "Edit" → tap the red minus icon in front of a source
2. Add `cydia.angelxwind.net` (Karen/angelXwind) and `apt.abcydia.com` (Leifeng)
3. In Cydia choose to uninstall `Cydia Substrate` and take a screenshot of the uninstall list. Do NOT confirm yet. Read carefully:
   - This will also uninstall many tweaks including XXTouch. In theory this is safe, but we cannot assume responsibility. If you have concerns, stop here and consult a professional.
   - After understanding the above, decide whether to confirm uninstall.
4. Install “Stashing 容量不足修正” and “Stashing Fix for Phœnix (9.3.5)”
5. Reboot as prompted
6. Re-activate the jailbreak. Space should now be sufficient; reinstall what was removed in step 3 if needed.

## Remove sources that may cause red/yellow errors

Remove all sources except Cydia/Telesphoreo and XXTouch (this will not cause any data loss):
- Including BigBoss, ModMyi, ZodTTD, and Ultrasn0w.
- Tap "Sources" → top-right "Edit" → tap the red minus icon in front of a source
- This is safe to do and will not cause any loss.

## Search for the error online

Common Cydia errors are well-documented online.
Search the red text to find a solution.

## Other attempts

If nothing helps, take a screenshot of the red error page and consult a professional.

---

Source: [What should I do if I cannot add the official XXTouch source in Cydia?](https://xxtouch.app/en/docs/FAQ/faq-0014.md)
Path: FAQ/faq-0014.md

# What should I do if I cannot add the official XXTouch source in Cydia?

First, confirm the official source URL:
- [**xxtouch.app**](https://xxtouch.app)

Ensure the device date, time, and time zone are correct:
- Go to **Settings → General → Date & Time** and [adjust manually](faq-0022.md) if needed

Then try the following:
- Ensure the network connection is available
- Remove all sources except Cydia/Telesphoreo and XXTouch (this will not cause any loss)
    - Tap “Sources” → top-right “Edit” → tap the red minus icon for a source
- Tap “Refresh” (top-left on the Sources page) and wait for it to finish
- If you see red or yellow errors, see [Install/update fails in Cydia (red/yellow text)](faq-0013.md)

---

Source: [What should I do if no packages appear under the official XXTouch source in Cydia?](https://xxtouch.app/en/docs/FAQ/faq-0015.md)
Path: FAQ/faq-0015.md

# What should I do if no packages appear under the official XXTouch source in Cydia?

First, confirm the official source URL:
- [**xxtouch.app**](https://xxtouch.app)

Then try the following:
- Tap “Refresh” (top-left on the Sources page) and wait for it to finish
- Check the XXTouch version in “Installed”
    - If the installed package version is newer than the one in the source, the source may not show it
    - This usually happens if a test build is installed on the device
    - This is normal; no further action is needed
- If not the above case, then:
    - Ensure the network is available
    - Remove all sources except Cydia/Telesphoreo and XXTouch (this will not cause any loss)
        - Tap “Sources” → top-right “Edit” → tap the red minus icon for a source
    - Tap “Refresh” and wait for it to finish
    - If there are red/yellow errors, see [Install/update fails in Cydia (red/yellow text)](faq-0013.md)

---

Source: [What should I do if XXTouch crashes, has no icon, or cannot be opened?](https://xxtouch.app/en/docs/FAQ/faq-0016.md)
Path: FAQ/faq-0016.md

# What should I do if XXTouch crashes, has no icon, or cannot be opened?

Try the following solutions in order.

---

## XXTouch icon missing from Home Screen

- If you are on Dopamine jailbreak with "Hide Jailbreak" enabled, **disable** that option.
- Otherwise, try `TrollStore` → `Rebuild Icon Cache`.
- If the icon still does not appear, reinstall XXTouch from Cydia or Sileo.

## Neither the TrollStore build of XXT nor TrollStore itself can be opened

Open the Persistence Helper app (e.g., if injected into `Tips`, open `Tips`).
Tap `Refresh App Registrations` and wait for it to finish; this should fix it.

## Reinstall XXTouch

Reinstall (no need to uninstall first) the latest XXTouch from Cydia or Sileo and ensure there are no errors.
Reboot the device (you may need to reactivate the jailbreak).

## Check tweak conflicts

Uninstall potentially conflicting tweaks from Cydia or Sileo, then reinstall XXTouch and reboot (you may need to reactivate the jailbreak).

---

Source: [What should I do if "sync failed" keeps appearing after installing XXTouch?](https://xxtouch.app/en/docs/FAQ/faq-0017.md)
Path: FAQ/faq-0017.md

# What should I do if "sync failed" keeps appearing after installing XXTouch?

Try the following according to your environment.

---

## If installed via Sileo

Try these one by one:

### Attempt 1

Tap Cancel, then choose a script.

### Attempt 2

Reinstall (no need to uninstall first) the latest XXTouch from Sileo and ensure there are no errors.
Reboot the device (you may need to reactivate the jailbreak).

### Attempt 3

1. Install **OpenSSH** via Sileo and ensure no errors occur (skip this if it is already installed).
2. In Sileo, choose to uninstall **Substitute** or **ElleKit** and take a screenshot of the uninstall list. Do NOT confirm yet; read carefully:
   - This will also uninstall many tweaks including XXTouch. In theory it is safe, but we cannot assume responsibility; if you have concerns, stop here and consult a professional.
   - After understanding, decide whether to confirm uninstall.
3. Install XXTouch from the source (you may need to reboot and reactivate the jailbreak) and ensure no errors occur.
4. Reboot again (you may need to reactivate the jailbreak).
5. If needed, reinstall the items removed in step 2 according to your screenshot.

### Attempt 4

Delete `/var/mobile/Media/1ferver/caches/daemon_cache.db` and reboot (you may need to reactivate the jailbreak).


## If installed via Cydia

Try these one by one:

### Attempt 1

Tap Cancel, then choose a script.

### Attempt 2

Reinstall (no need to uninstall first) the latest XXTouch from Cydia and ensure there are no red errors (see [Install/update fails in Cydia (red/yellow text)](faq-0013.md)).
Reboot (you may need to reactivate the jailbreak).

### Attempt 3

1. Install **OpenSSH** via Cydia and ensure no red errors occur (skip this if it is already installed).
2. Refresh Cydia sources and update all base dependencies, ensuring no red errors occur.
3. Reinstall (no need to uninstall first) the core components and XXTouch, ensuring no red errors occur:
   - iOS below 11: **Cydia Substrate**, **UIKit Tools**, and XXTouch
   - iOS 11 and later: **Tweak Injector**, **Substitute**, **Substrate Compatibility Layer**, **UIKit Tools**, and XXTouch
4. Reboot the device (you may need to reactivate the jailbreak).

### Attempt 4

1. In Cydia, choose to uninstall **Cydia Substrate** (on iOS 11 and later, uninstall **Substitute**) and take a screenshot of the uninstall list. Do NOT confirm yet; read carefully:
   - This will also uninstall many tweaks including XXTouch. In theory it is safe, but we cannot assume responsibility; if you have concerns, stop here and consult a professional.
   - After understanding, decide whether to confirm uninstall.
2. Install XXTouch from the source (you may need to reboot and reactivate the jailbreak) and ensure no red errors occur.
3. Reboot again (you may need to reactivate the jailbreak).
4. If needed, reinstall the items removed in step 1 according to your screenshot.

### Attempt 5

Delete `/var/mobile/Media/1ferver/caches/daemon_cache.db` and reboot (you may need to reactivate the jailbreak).

---

Source: [What should I do if XXTouch repeatedly asks to respring or cannot communicate with the server or daemon?](https://xxtouch.app/en/docs/FAQ/faq-0018.md)
Path: FAQ/faq-0018.md

# What should I do if XXTouch repeatedly asks to respring or cannot communicate with the server or daemon?

Try the following according to your environment.

---

## If installed via Sileo

Try these one by one:

### Attempt 1

Tap Cancel, then choose a script.

### Attempt 2

Reinstall (no need to uninstall first) the latest XXTouch from Sileo and ensure there are no errors.
Reboot the device (you may need to reactivate the jailbreak).

### Attempt 3

1. Install **OpenSSH** via Sileo and ensure no errors occur (skip this if it is already installed).
2. In Sileo, choose to uninstall **Substitute** or **ElleKit** and take a screenshot of the uninstall list. Do NOT confirm yet; read carefully:
   - This will also uninstall many tweaks including XXTouch. In theory it is safe, but we cannot assume responsibility; if you have concerns, stop here and consult a professional.
   - After understanding, decide whether to confirm uninstall.
3. Install XXTouch from the source (you may need to reboot and reactivate the jailbreak) and ensure no errors occur.
4. Reboot again (you may need to reactivate the jailbreak).
5. If needed, reinstall the items removed in step 2 according to your screenshot.

### Attempt 4

Delete `/var/mobile/Media/1ferver/caches/daemon_cache.db` and reboot (you may need to reactivate the jailbreak).


## If installed via Cydia

Try these one by one:

### Attempt 1

Tap Cancel, then choose a script.

### Attempt 2

Reinstall (no need to uninstall first) the latest XXTouch from Cydia and ensure there are no red errors (see [Install/update fails in Cydia (red/yellow text)](faq-0013.md)).
Reboot (you may need to reactivate the jailbreak).

### Attempt 3

1. Install **OpenSSH** via Cydia and ensure no red errors occur (skip this if it is already installed).
2. Refresh Cydia sources and update all base dependencies, ensuring no red errors occur.
3. Reinstall (no need to uninstall first) the core components and XXTouch, ensuring no red errors occur:
   - iOS below 11: **Cydia Substrate**, **UIKit Tools**, and XXTouch
   - iOS 11 and later: **Tweak Injector**, **Substitute**, **Substrate Compatibility Layer**, **UIKit Tools**, and XXTouch
4. Reboot the device (you may need to reactivate the jailbreak).

### Attempt 4

1. In Cydia, choose to uninstall **Cydia Substrate** (on iOS 11 and later, uninstall **Substitute**) and take a screenshot of the uninstall list. Do NOT confirm yet; read carefully:
   - This will also uninstall many tweaks including XXTouch. In theory it is safe, but we cannot assume responsibility; if you have concerns, stop here and consult a professional.
   - After understanding, decide whether to confirm uninstall.
2. Install XXTouch from the source (you may need to reboot and reactivate the jailbreak) and ensure no red errors occur.
3. Reboot again (you may need to reactivate the jailbreak).
4. If needed, reinstall the items removed in step 1 according to your screenshot.

### Attempt 5

Delete `/var/mobile/Media/1ferver/caches/daemon_cache.db` and reboot (you may need to reactivate the jailbreak).

---

Source: [Limitations of rootless/roothide/TrollStore builds of XXTouch](https://xxtouch.app/en/docs/FAQ/faq-0019.md)
Path: FAQ/faq-0019.md

# Limitations of rootless/roothide/TrollStore builds of XXTouch

On iOS 15 and later, the system partition is read-only.

---

## TrollStore build limitations

- `alerthelper` module does not work properly
- `dialog` and `webview` are less smooth than in a full jailbreak environment
- Cannot use `os.execute` or `io.popen`

## TrollStore build advantages

- Does not rely on a jailbreak environment
- Can use a Home Screen widget to start automatically on boot

## Bootstrap jailbreak environment limitations

- XXTouch daemon does not auto-start with Bootstrap
- `alerthelper` module does not work properly
- `dialog` and `webview` are less smooth than in a full jailbreak environment
- The software keyboard cannot be shown inside `webview` floating windows
- See [Notes for XXTouch in Bootstrap environments](faq-0021.md#xxtouch-bootstrap-notes)

## Dopamine-Roothide limitations

- Almost no limitations
- See [What’s special about roothide?](faq-0021.md)

## Rootless jailbreak limitations

- Almost no limitations

---

Source: [License shows invalid even though it hasn’t expired](https://xxtouch.app/en/docs/FAQ/faq-0020.md)
Path: FAQ/faq-0020.md

# License shows invalid even though it hasn’t expired

Please check the following in order:

1. Ensure the device date, time, and time zone are correct
   - Time tolerance is 5 minutes. Go to **Settings → General → Date & Time** to [adjust manually](faq-0022.md) if needed.

2. Ensure the device has a working internet connection
   - Proxies or VPNs on the device may interfere.

If none of the above resolves the issue, take a screenshot and contact your reseller.

---

Source: [What is special about roothide environments?](https://xxtouch.app/en/docs/FAQ/faq-0021.md)
Path: FAQ/faq-0021.md

# What is special about roothide environments?

Roothide is a third type of jailbreak environment, distinct from rootful and rootless.

---

## Differences from rootful/rootless

Unlike traditional jailbreaks, in roothide the "jailbreak root (jbroot)" and the "system root (rootfs)" are separate.
`jbroot` is mounted inside `rootfs` at a random path, and `rootfs` is also bind-mounted back at `jbroot/rootfs/`.


## System root (rootfs)

In roothide, the system root is the iOS root directory. It is unmodified and contains no extra paths.


## Jailbreak root (jbroot)

In roothide, `jbroot` is mounted under `rootfs` at a random path,
usually something like `/var/containers/Bundle/Application/.jbroot-XXXXXXXXXXXXXXXX/` (the X characters are random).
Use the `jbroot` function to convert a normal path to its jbroot path.
For example, to access `/var/mobile/Media/1.txt` inside jbroot, use `jbroot("/var/mobile/Media/1.txt")`.
In a script, `f = io.open(jbroot("/var/mobile/Media/1.txt"), "r")` will actually open:
```bash
/var/containers/Bundle/Application/.jbroot-XXXXXXXXXXXXXXXX/var/mobile/Media/1.txt
```


## Shell environment

As mentioned, jbroot is mounted at a random path inside rootfs.
But in shell environments (e.g., deb install scripts), you cannot know where jbroot is mounted inside rootfs.
Therefore, roothide sets the runtime root for shell scripts to `jbroot`.
That is, `/Applications/XXTExplorer.app` in a deb will be installed to:
```bash
/var/containers/Bundle/Application/.jbroot-XXXXXXXXXXXXXXXX/Applications/XXTExplorer.app
```
This ensures jailbroken packages do not pollute the system root.
However, it introduces a problem when using `os.execute` or `io.popen` in XXTouch scripts,
since they execute via bash/zsh. For example, calling `os.execute("/usr/bin/hidutil list")` will actually run:
```bash
/var/containers/Bundle/Application/.jbroot-XXXXXXXXXXXXXXXX/usr/bin/hidutil list
```
This prevents direct access to rootfs paths from shell.
To solve this, roothide bind-mounts the system root back to `jbroot/rootfs/`.
Thus, `os.execute("/rootfs/usr/bin/hidutil list")` will actually run:
```bash
/usr/bin/hidutil list
```


## File and directory mirrors

Certain files/directories inside `jbroot` are symlinked to the original `rootfs`:

| Path inside jbroot |
| - |
| /dev |
| /private/preboot |
| /var/containers |
| /var/mobile/Containers |
| /usr/share/misc/trace.codes |
| /usr/share/zoneinfo |
| /etc/hosts.equiv |
| /etc/hosts |
| /var/run/utmpx |
| /var/db/timezone |
| /System/Library/CoreServices/SystemVersion.plist |

In addition, XXTouch’s script root `/var/mobile/Media/1ferver` in jbroot is also symlinked into rootfs.
These paths are accessible from both jbroot and rootfs.
[Reference](https://github.com/roothide/Developer/blob/main/filemirror.md)


## XXTouch in Bootstrap environments {#xxtouch-bootstrap-notes}

### No auto-start

On devices using Bootstrap-Roothide semi-jailbreak, after rebooting and re-activating Bootstrap,
XXTouch daemon does not start automatically. Open the XXTouch app; it will close automatically and display `Starting XXTouch Daemon...`.
Within 20 seconds the daemon should be running.

### No SpringBoard injection

If Bootstrap is used without enabling SpringBoard injection via Serotonin, UI-related script features are unavailable:
- `dialog`, `webview`, and other features that create top-level UI will be affected
- `alerthelper` cannot handle SpringBoard alerts

### Use XXTouch to remove potentially detectable files in Bootstrap-Roothide

```lua
local noexecute = require('no_os_execute')

function remove_sys_app_caches(name)
    noexecute.rm_rf('/var/root/Library/WebKit/'..name)
    noexecute.rm_rf('/var/root/Library/Caches/'..name)
    noexecute.rm_rf('/var/root/Library/HTTPStorages/'..name)
    noexecute.rm_rf('/var/root/Library/SplashBoard/Snapshots/'..name)
    noexecute.rm_rf('/var/root/Library/Saved Application State/'..name..'.savedState')
    noexecute.rm_rf('/var/root/Library/Preferences/'..name..'.plist')

    noexecute.rm_rf('/var/root/Library/WebKit/'..name)
    noexecute.rm_rf('/var/mobile/Library/Caches/'..name)
    noexecute.rm_rf('/var/mobile/Library/HTTPStorages/'..name)
    noexecute.rm_rf('/var/mobile/Library/SplashBoard/Snapshots/'..name)
    noexecute.rm_rf('/var/mobile/Library/Saved Application State/'..name..'.savedState')
    noexecute.rm_rf('/var/mobile/Library/Preferences/'..name..'.plist')
end

remove_sys_app_caches('com.opa334.Dopamine')
remove_sys_app_caches('org.coolstar.SileoStore')
remove_sys_app_caches('ws.hbang.Terminal')
remove_sys_app_caches('pisshill.usprebooter')
remove_sys_app_caches('com.samiiau.loader')
remove_sys_app_caches('kr.xsf1re.vnodebypass')
remove_sys_app_caches('com.serena.Antoine')
remove_sys_app_caches('wiki.qaq.TrollFools')
remove_sys_app_caches('com.tigisoftware.Filza')
remove_sys_app_caches('com.tigisoftware.Filza000')
remove_sys_app_caches('com.tigisoftware.ADManager')
remove_sys_app_caches('com.ichitaso.otadisablerts')
remove_sys_app_caches('chaoge.ChargeLimiter')
remove_sys_app_caches('com.xxtouch.XXTExplorer')

noexecute.rm_rf('/private/var/mobile/Library/Filza')
noexecute.rm_rf('/private/var/mobile/.ssh')
noexecute.rm_rf('/private/var/root/.ssh')
noexecute.rm_rf('/private/var/mobile/offsets.txt')
noexecute.rm_rf('/private/var/mobile/offsets.txt')
noexecute.rm_rf('/private/var/mobile/Serotonin.jp2')
noexecute.rm_rf('/private/var/mobile/Documents/kfund_offsets.plist')
noexecute.rm_rf('/private/var/iomfb_bics_daemon')
```

Why do these files exist?
Although roothide installs jailbreak apps under random jbroot paths, it does not confine their runtime to those paths.
So after running, caches or other files may still be written to the corresponding locations in rootfs.

Apps may also detect the SSH port. If necessary, disable SSH in Bootstrap settings to avoid detection.

---

Source: [Where to adjust iOS date and time?](https://xxtouch.app/en/docs/FAQ/faq-0022.md)
Path: FAQ/faq-0022.md

# Where to adjust iOS date and time?

1. Open the **Settings** app.
2. Navigate to **General**.
3. Tap **Date & Time**.

---

Source: [What should I do if the Color Picker, Editor, or LAN Controller cannot discover the device?](https://xxtouch.app/en/docs/FAQ/faq-0023.md)
Path: FAQ/faq-0023.md

# What should I do if the Color Picker, Editor, or LAN Controller cannot discover the device?

Check the following:

- Ensure no firewall rules on the computer or router are blocking traffic
- Confirm the device and computer are on the **same LAN**
- Disable any proxy or VPN on the device
- Make sure the device screen is **unlocked**
- Verify the computer can ping the device

Finally, make sure the device has the [Remote Switch](/en/docs/ABC/index.md#how-to-enable-remote-interface) enabled.

---

Source: [Why does Scan-to-Download show “Frame box failed to load”?](https://xxtouch.app/en/docs/FAQ/faq-0024.md)
Path: FAQ/faq-0024.md

# Why does Scan-to-Download show “Frame box failed to load”?

If you are a script distributor (author), see [XXTouch Scan-to-Download protocol](/en/docs/URLScheme/Download.md).
If you are a script user, please ask your distributor (author) to read the article above.

---

Source: [How to record a script?](https://xxtouch.app/en/docs/FAQ/faq-0025.md)
Path: FAQ/faq-0025.md

# How to record a script?

By default:

1. Press the **Volume** button once to bring up the action menu.
2. Choose **Record** to start recording.
3. Press the **Volume** button once again to finish.

You can customize the hotkey in `More → Key Settings`.

See also: [How to record a script?](/en/docs/ABC/index.md#how-to-record-script)

---

Source: [How do I run a script?](https://xxtouch.app/en/docs/FAQ/faq-0026.md)
Path: FAQ/faq-0026.md

# How do I run a script?

1. Launch the XXTouch app — you will see the **My Scripts** page.
2. Tap the script filename to select it.
3. Press the **Volume** button once to bring up the action menu, then choose **Start Script**.
4. Press the **Volume** button again to pause or stop the running script.

You can customize the hotkey in `More → Key Settings`.

See also: [How to run the selected script?](/en/docs/ABC/index.md#how-to-run-selected-script)

---

Source: [How do I select a script to run?](https://xxtouch.app/en/docs/FAQ/faq-0027.md)
Path: FAQ/faq-0027.md

# How do I select a script to run?

Launch the XXTouch app to open the **My Scripts** page, then tap the filename of the script you want to select.

---

Source: [How do I edit scripts on the device?](https://xxtouch.app/en/docs/FAQ/faq-0028.md)
Path: FAQ/faq-0028.md

# How do I edit scripts on the device?

1. Launch the XXTouch app to open the **My Scripts** page.
2. Tap the `ⓘ` icon to the right of the script file.
3. Tap the `</>` button to open the built-in editor.

---

Source: [How to encrypt a script?](https://xxtouch.app/en/docs/FAQ/faq-0029.md)
Path: FAQ/faq-0029.md

# How to encrypt a script?

- Visual guide: [How to encrypt a script](/en/docs/ABC/index.md#how-to-encrypt-script)

---

Source: [What can scripts do?](https://xxtouch.app/en/docs/FAQ/faq-0030.md)
Path: FAQ/faq-0030.md

# What can scripts do?

See the [XXTouch iOS Developer Handbook](/en/docs/handbook/index.md).

---

Source: [Can encrypted scripts be decrypted?](https://xxtouch.app/en/docs/FAQ/faq-0031.md)
Path: FAQ/faq-0031.md

# Can encrypted scripts be decrypted?

No.
The process from source code to encrypted script is one-way and irreversible.
Source code can be encrypted into an encrypted script, but encrypted scripts cannot be restored to source code.

---

Source: [Can XXTouch run on a computer?](https://xxtouch.app/en/docs/FAQ/faq-0032.md)
Path: FAQ/faq-0032.md

# Can XXTouch run on a computer?

No.
XXTouch is iOS-only.

---

Source: [Can XXTouch run on Android?](https://xxtouch.app/en/docs/FAQ/faq-0033.md)
Path: FAQ/faq-0033.md

# Can XXTouch run on Android?

No.
XXTouch is iOS-only.

---

Source: [How do I install TrollStore on a device?](https://xxtouch.app/en/docs/FAQ/faq-0034.md)
Path: FAQ/faq-0034.md

# How do I install TrollStore on a device?

If you run into any issues, try again in a network environment that is not subject to restrictive traffic filtering.

---

## Supported versions

- iOS 14.0 – 16.6.1
- iOS 16.7 RC (20H18)
- iOS 17.0.0

TrollStore **cannot be installed** on iOS 16.7.x or iOS 17.0.1 and later.

---

## iOS 15.1 and below

Follow the methods listed at [https://ios.cfw.guide/installing-trollstore/](https://ios.cfw.guide/installing-trollstore/).

---

## iOS 15.2 – 16.6.1, 16.7 RC (20H18), 17.0.0

Use [TrollRestore](https://github.com/JJTech0130/TrollRestore/releases) to install `TrollStore` (TrollHelper) onto the device.

### Preparation

- Download the matching desktop build of [TrollRestore](https://github.com/JJTech0130/TrollRestore/releases) to your computer
- **Windows** users must install iTunes beforehand, or install the Apple device drivers via i4Tools
- Make sure `Find My iPhone` is disabled on the device (`Settings → [iCloud account] → Find My`)
- Make sure the official Apple `Tips.app` from the App Store is installed on the device

### Installation steps

1. Launch `TrollRestore` from a terminal on your computer
2. When prompted for an app name, enter `Tips` and press Enter
    - If you see `Failed to find the removable system app 'Tips.app'`, install the official `Tips.app` from the App Store first
    - If you see `Find My must be disabled in order to use this tool`, disable `Find My iPhone` under `Settings → [iCloud account] → Find My`
3. Wait for the device to reboot automatically
4. After reboot, open `Tips` on the device
5. Tap `Install TrollStore` and wait for the respring
6. Return to the Home Screen and launch `TrollStore`
7. Open `TrollStore → Settings → Install Persistence Helper` and select `Tips` to install the persistence helper (**this step is important**)

---

## TrollStore icon turns black / apps installed via TrollStore crash

Open `Tips` → tap `Refresh App Registrations`.

---

Source: [Getting Started](https://xxtouch.app/en/docs/ABC/index.md)
Path: ABC/README.md

# Getting Started

---

## How to activate a license code? {#how-to-activate-license}

After purchasing a license code, follow the steps shown below:
![activate-license.gif-433.5kB](授权码如何激活.gif)

---

## Main UI overview

![main-ui-overview.png-101kB](主界面说明图示.png)

---

## How to run the selected script? {#how-to-run-selected-script}

By default, press the Volume button once from any screen to bring up the action menu:
![volume-longpress-menu.jpg-24.4kB](默认长按音量键会出现.jpg)
Choose **Start Script** to run the currently selected script.
**Note:** You can customize the shortcut in `More → Key Settings`.

---

## How to record a script? {#how-to-record-script}

By default, press the Volume button once from any screen to bring up the action menu:
![volume-longpress-menu.jpg-24.4kB](默认长按音量键会出现.jpg)

Choose **Record** to start recording.
Press the Volume button once again to finish:
![record-finished.jpg-32kB](录制完成提示.jpg)

**Note:** You can customize the shortcut in `More → Key Settings`.

---

## How to encrypt a script? {#how-to-encrypt-script}

Before proceeding, make sure:
- The device has the latest version of XXTouch installed
- The device and computer are on the same LAN
- The device and computer can reach each other over the network

Then enable the Remote Interface on the device (see [How to enable the Remote Interface?](#how-to-enable-remote-interface)) and follow the steps below:
![encrypt-locally.png-49.3kB](如何本地加密脚本.png)

---

## How to enable the Remote Interface? {#how-to-enable-remote-interface}

Open the XXTouch app, navigate to `More → Remote Service`, and toggle it on:
![enable-remote.gif-86.4kB](激活远程开关.gif)
